Python 无法通过 TravisCI 上存在且位于 PATH 中的子进程启动命令

标签 python subprocess environment-variables travis-ci

作为我的 Python 包的一部分,我正在尝试启动 wine通过Python的subprocess.Popen 。简而言之,(仅)在 Travis CI 上,尽管 wine位于PATH ,我收到以下错误:FileNotFoundError: [Errno 2] No such file or directory: 'wine': 'wine'

我忽略了什么?

<小时/>

好的:wine命令位于/opt/wine-staging/bin ,这也是 PATH 的一部分。它被添加到 before_install .travis.yml的部分.

确定:正在运行 wine --versionbefore_install部分有效,显示正确的 Wine 版本。

确定:正在检查os.environ确认 Python 看到 PATH 的正确内容包括/opt/wine-staging/bin .

确定:检查 /opt/wine-staging/bin 的内容来 self 的 Python 脚本 os.listdir('/opt/wine-staging/bin/')确认wine存在。

不正常:正在运行 subprocess.Popen(['which', 'wine'], stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()从 Python 脚本内部根本不会产生任何输出(但也不会以有意义的方式失败)。

不正常:正在运行 subprocess.Popen(['wine', '--version'], stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()失败并显示 FileNotFoundError: [Errno 2] No such file or directory: 'wine': 'wine' .

最佳答案

在 openSUSE Linux 上,subprocess.Popen将继承 os.environ 中的所有变量隐式地,即使 env参数改变。以下内容将正常工作:

subprocess.Popen(
    ['wine', '--version'],
    stdout = subprocess.PIPE, stderr = subprocess.PIPE,
    env = {'FOO': 'bar'}
    ).communicate()

在 Travis CI 的 Ubuntu 变体上,由于某些奇怪的原因,变量来自 os.environ如果 env 则不会被继承参数的使用方式与上面类似。有两种方法可以解决此问题: 要么不更改 env参数或复制 os.environ 中的所有数据进入 env 然后修改它:

# Workaround 1: Do not use "env"
subprocess.Popen(
    ['wine', '--version'],
    stdout = subprocess.PIPE, stderr = subprocess.PIPE
    ).communicate()

# Workaround 2: Copy all data from "os.environ" into "env" before altering it
envvar = {k: os.environ[k] for k in os.environ.keys()}
envvar.update({'FOO': 'bar'})
subprocess.Popen(
    ['wine', '--version'],
    stdout = subprocess.PIPE, stderr = subprocess.PIPE,
    env = envvar
    ).communicate()

关于Python 无法通过 TravisCI 上存在且位于 PATH 中的子进程启动命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57971856/

相关文章:

php - PythonPATH 和 PHP

Java 系统环境变量

python - scikit 学习 : update countvectorizer after selecting k best features

c++ - boost Python 可移植性问题

python - 在Python多处理中共享和编辑numpy数组

python - 如何在用户提示下流式传输子进程输出?

python - 为什么这些 Python 脚本会出现语法错误?

python - 子进程:无法将 '_io.BufferedReader' 对象隐式转换为 str

python - 终止子进程后终端文本变得不可见

linux - docker容器中的环境变量在哪里