在我得到反对票之前,这不是重复的。我已经用尽了谷歌和 SO。在 SO 中,存在关于如何安装 Python 模块的问题。但我的问题是创建一个 venv
并以编程方式将模块安装到这个创建的 venv
中。我已经尝试了一些东西;
我的示例代码
def create_venv_install_requirements(venv_folder, filename):
print(f'Creating a new virtual environment')
virtualenv.create_environment(venv_folder)
activate_file = os.path.join(venv_folder, 'Scripts', 'activate_this.py')
print('Installing requirements')
with open(filename) as f:
requirements = f.readlines()
for item in requirements:
exec(open(activate_file).read(), globals())
subprocess.call(f'pip install {item}')
# pip.main('install', item) this does not work as well
我面临的问题是我可以成功创建一个 venv
,但是无法在创建的 venv
中安装模块,而是在系统范围内安装它们。如何在激活的 venv
中安装包?
最佳答案
听起来您的脚本调用了错误的 pip
,尽管您正在激活它。您可以在虚拟环境中显式调用pip
(即使没有像这样激活它):
subprocess.call('{venv_folder}/bin/pip install {item}')
但实际上不要那样做,因为如果你在文件中有一个需求列表,你应该调用:
subprocess.call('{venv_folder}/bin/pip install -r {filename}')
...当然,在这种情况下,您不需要打开需求文件并自行遍历它。
注意:对于Windows系统,将bin
替换为Scripts
关于python - 如何以编程方式在 virtualenv 中安装 Python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48087778/