Python 调用不需要虚拟环境的子进程

Python calling subprocess that requires no virtual environment

我有一个 Python 3.6 脚本,它使用子进程调用第三方工具。

main_script.py:

#!/usr/bin/env python
import subprocess
result = subprocess.run(['third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

问题是,main_script.py 必须 运行 来自虚拟环境,而 third-party-tool 必须 运行 来自任何虚拟环境。

我对 third-party-tool 了解不多,只是它在我的道路上。在我有一个虚拟环境处于活动状态时调用它会导致它卡住并在以后抛出异常。我不知道它是使用默认的 python 二进制文件还是它启动自己的虚拟环境并在其中执行操作。它不是 Python 脚本,但显然以某种方式调用了一个脚本。

如何告诉子进程退出我的虚拟环境和 运行 默认 shell 环境中的命令?

我研究了几个类似的问题:

来自子流程的文档:

https://docs.python.org/3/library/subprocess.html

可接受的参数是

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
    capture_output=False, shell=False, cwd=None, timeout=None, check=False,
    encoding=None, errors=None, text=None, env=None, universal_newlines=None)

特别是,

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen.

因此,传递一个空字典 env={}(从空环境开始)并使用 bash --login(运行 作为登录名 shell,读取 env defaults)应该可以技巧。

subprocess.run(['bash', '--login', '-c', '/full/path/to/third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={})

感谢您的帮助,nullUser;您的解决方案是对我的问题的简洁而正确的回答。

但是,当我试用它时,我的第三方工具现在由于某些其他(未知)原因而失败。可能有一些我不知道的其他环境变量随着新的 shell 丢失了。幸运的是,我找到了一个替代解决方案,我将与其他遇到困难的人分享。

我的解决方案

据我所知,进入虚拟环境对我的环境的唯一区别是为我的 PATH 变量添加一个新路径,并添加变量 VIRTUAL_ENV.

我可以通过创建我的环境的副本来复制外部虚拟环境行为,其中我:

  • 删除那个VIRTUAL_ENV环境变量和
  • 从 PATH 中删除 python 前缀。

例子

my_script.py

my_script.py 实施我的解决方案:

#!/usr/bin/env python
import subprocess, os, sys

env = os.environ.copy()
if hasattr(sys,'real_prefix'):
    # If in virtual environment, gotta forge a copy of the environment, where we:
    # Delete the VIRTUAL_ENV variable.
    del(env['VIRTUAL_ENV'])

    # Delete the "/home/me/.python_venv/main/bin:" from the front of my PATH variable.
    orig_path = env['PATH']
    virtual_env_prefix = sys.prefix + '/bin:'
    env['PATH'] = orig_path.replace(virtual_env_prefix, '')

# Pass the environment into the third party tool, modified if and when required.
subprocess.run(['./third-party-tool'], shell=False, env=env)

第三方工具

third-party-tool 被模拟为一个脚本,告诉您它是否在虚拟环境中并打印出环境变量。在这个例子中,third-party-tool 是一个 Python 脚本,但通常它可能不是。

#!/usr/bin/env python
# third-party-tool
import sys, os
in_venv = hasattr(sys, 'real_prefix')
print('This is third-party Tool and you {} in a virtual environment.'.format("ARE" if in_venv else "ARE NOT"))
os.system('env')

测试

现在我尝试从外部虚拟环境、内部虚拟环境和虚拟环境中的 python 脚本调用第三方工具,捕获输出。

[me@host ~]$ ./third-party-tool > without_venv.txt
# Now I activate virtual environment
(main) [me@host ~]$ ./third-party-tool > within_venv.txt
(main) [me@host ~]$ ./my_script.py > within_venv_from_python.txt

注意:输出如下所示: 这是第三方工具,您不在虚拟环境中。 (继续打印出 KEY=VALUE 环境变量列表)

我使用我最喜欢的 diff 工具比较输出。 within_venv_from_python.txtwithout_venv.txt 相同,这是一个好兆头(在这两种情况下,third-party-tool 使用相同的环境变量运行,并表明它不在矩阵中)。实施此解决方案后,我的实际第三方工具似乎可以正常工作。