gpt4 book ai didi

python - 如何以编程方式在 virtualenv 中安装 Python 模块?

转载 作者:太空宇宙 更新时间:2023-11-04 02:35:10 25 4
gpt4 key购买 nike

在我得到反对票之前,这不是重复的。我已经用尽了谷歌和 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com