无法从 Python 脚本(子进程 | powershell)激活 virtualenv

Unable to activate virtualenv from Python script (subprocess | powershell)

从 Windows 的 powershell 激活 virtualenv 非常简单,通过 ./venv/Scripts/activate 命令,或使用如下绝对路径:

但是当我想从 Python 脚本中执行相同的命令时,该脚本在 powershell 中执行命令,virtualenv 没有激活,我不能 运行 pip install something virtualenv 中的命令。这意味着我无法在 virtualenv 中添加包甚至升级 pip(当然是因为它没有正确激活)。

备注

我对代码的实现很有信心,因为它对其他命令也很有效。唯一的问题可能是发送到 powershell 的 C:/temp/venv/Scripts/activate 命令。在 Linux 中寻找类似 source 的命令来激活该 virtualenv。

这是我的代码:

installer.py 脚本:运行powershell 中的不同命令 subprocess,结果 returns。

# installer.py
class Installer:
   def run(command):
        # Some code here
        proc = subprocess.Popen(
            [ 'powershell.exe', command ],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        # Some code here

install.py 脚本:向安装程序发送命令 class

# install.py
from installer import Installer

installer = Installer()
installer.run('C:/temp/venv/Scripts/activate')

解决方案

原来我不需要激活 virtualenv。我可以轻松地 运行 pip install 命令发送以下命令到子进程:

installer.run('C:/temp/venv/Scripts/python.exe -m pip install somepackage')