【发布时间】:2021-09-24 01:48:54
【问题描述】:
import subprocess
cmd = "source ~/.bash_profile || echo hello"
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
(out, err) = proc.communicate()
code = proc.returncode
print(f"code:{code}, out:{out}, err:{err}")
输出:
code:1, out:b'', err:b'/bin/sh: /Users/xxx/.bash_profile: 没有这样的文件或目录\n'
我没有 bash_profile,但为什么 out 不包含 "hello"?
【问题讨论】:
-
这似乎更像一个 bash 问题而不是 python 问题
-
这是在 MacOS 上吗?您使用的是 bash 还是 zsh?您的代码在 Linux 上按预期工作。
-
@TimRoberts 我正要说同样的话,代码在 debian 10 上使用 bash 打印
code:0, out:b'hello\n', err:b'/bin/sh: 1: source: not found\n'(如预期的那样) -
是的,它在 MacOS 上
-
@jemand771 它与 Python 有关,因为当您在 macOS 终端上直接执行
source ~/.bash_profile_does_not_exist || echo hello时,您会看到 both 错误 和 "你好”字符串。但是当你用subprocess把它放到这样的Python脚本中时,“你好”确实不会出现。
标签: python bash macos subprocess