为什么Python脚本从批处理文件调用时无法导入通过pip安装到虚拟环境的模块?

问题描述 投票:0回答:1

我编写了一个批处理文件,该文件应执行以下操作:

  • 创建虚拟环境
  • 激活虚拟环境
  • 在虚拟环境中使用 pip 从 GitHub 存储库安装模块
  • 执行在虚拟环境中导入所述模块的Python脚本

这里有一些示例代码,可以让我了解我已经拥有的内容:

批处理文件:

file.bat

python3 -m venv myenv
call .\myenv\Scripts\activate
pip3 install git+https://github.com/user/themodule_repo.git
python3 script.py

Python 脚本:

script.py

import themodule
themodule.function()

script.py
返回
ModuleNotFoundError: No module named 'themodule'
,但模块本身可以在
.\myenv\Lib\site-packages\themodule
中找到。

从命令行执行

file.bat
script.py
返回
ModuleNotFoundError: No module named 'themodule'
,但模块本身可以在
.\myenv\Lib\site-packages\themodule
中找到。

当我在命令行中手动执行以下命令时,一切都按预期工作。

C:\somepath> python3 -m venv myenv
C:\somepath> .\myenv\Scripts\activate
(myenv) C:\somepath> pip3 install git+https://github.com/user/themodule_repo.git
(myenv) C:\somepath> python3

>>> import themodule
>>> themodule.function()
>>>

我在 Windows 10 64 位上使用 Python 3.9.5。

python batch-file virtualenv python-venv
1个回答
0
投票

您使用哪种外壳?如果你使用的话会有什么不同吗

call .\myenv\Scripts\activate.bat

call .\myenv\Scripts\activate.ps1

© www.soinside.com 2019 - 2024. All rights reserved.