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

标签 python subprocess virtual environment

我有一个 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 环境中运行命令?

我检查了几个类似的问题:
  • Running subprocess within different virtualenv with python -- 在第一种情况下,他们通过使用特定版本的 Python 调用脚本来指定环境。 third-party-tool不是 Python 脚本(我相信它是 bash)。
  • Python subprocess/Popen with a modified environment -- 在第二种情况下,他们正在调整现有的环境变量,这看起来很有希望,但我想重置为默认环境,而且我不确定我是否一定知道我需要清除或重置哪些变量。
  • 最佳答案

    从子流程的文档中:

    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/

    相关文章:

    python - scipy.optimize.fmin 有 2 个变量。如何让它发挥作用

    python - 比较字符串: file and lists

    python runpy.run_module 退出代码

    Python杀死一个子进程(启动另一个进程)并再次启动它

    c++ - 多重继承和纯虚函数

    c++ - ABC 虚拟 OStream 插入运算符

    python - 如何将Django的评论表单默认标签名称更改为中文?

    python - 使用 matplotlib 的 ax.text 打印变量会打印值列表而不是数字?

    python - 让子进程输出到文件和标准输出/标准错误的最简单的接口(interface)?

    C++:覆盖纯虚拟成员变量?