我有一个 Python 3.6 脚本,它使用 subprocess 调用第三方工具。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 环境中运行命令?
我检查了几个类似的问题:
third-party-tool
不是 Python 脚本(我相信它是 bash)。 最佳答案
从子流程的文档中:
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 默认值)应该可以解决问题。subprocess.run(['bash', '--login', '-c', '/full/path/to/third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={})
关于不需要虚拟环境的Python调用子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55739404/