如何在虚拟环境中编程安装Python模块?

4
在我被贴上踩的标签之前,先声明这不是个重复问题。我已经在谷歌和stackoverflow尝试过了。在stackoverflow上,有些问题涉及如何安装Python模块。但我的问题是如何通过编程方式创建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中安装包?


subprocess.call(f'pip install {item}') 是用来做什么的? - Peter Wood
1
在运行 pip 前,你是否已经激活了 venv?请执行 source venv/bin/activate 来激活 venv。 - taoufik A
@PeterWood 这是 Python 的 f-string(一种在 3.6 及更高版本中可用的新格式化语法)。 - larsks
抱歉,我的错。问题在于当您调用子进程时,系统会创建一个新的进程。 - taoufik A
@taoufikA。我不会Bash。如果你看不出来我的代码,我正在使用Windows系统(activate_file = os.path.join(venv_folder, 'Scripts', 'activate_this.py'))。 - Vino
显示剩余5条评论
1个回答

3

看起来您的脚本调用了错误的 pip,即使您已经激活了虚拟环境。您可以在虚拟环境中明确地调用 pip(甚至无需激活)如下:

subprocess.call('{venv_folder}/bin/pip install {item}')

但实际上不要这样做,因为如果您有一个文件中的要求列表,您应该只需调用:
subprocess.call('{venv_folder}/bin/pip install -r {filename}')

当然,在这种情况下,您不需要打开要求文件并自己迭代。

注意:对于Windows系统,请将bin替换为Scripts


实际上我是使用 exec(open(activate_file).read(), globals()) 来激活它的。但是谢谢,我会尝试你的方法并回报结果。 - Vino
抱歉,我错过了那一行。但是尝试一下这个,因为似乎Python在错误的位置寻找“pip”。 - larsks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接