Python subprocess.Popen 奇怪的行为

标签 python subprocess popen

我正在尝试运行一个进程,当它完成时,读取 stderr 和 stdout。我发现使用 Python 执行此操作的唯一方法是创建一个 subprocess.Popen,将 subprocess.PIPE 作为 stderr 和 stdout args,然后读取 Popen.stderr 和 Popen.stdout 文件描述符。

In [133]: subprocess.call(['python', '-c', "import sys; sys.exit(1)"])
Out[133]: 1

In [134]: p = subprocess.Popen(['python', '-c', "import sys; sys.exit(1)"])

In [135]: p.returncode

In [136]:

我可以获得 subprocess.call 的返回码,但我无法获得 subprocess.Popen 的返回码。我还尝试阅读 stderr 以查看 subprocess.Popen 是否真的运行命令:

In [143]: p = subprocess.Popen(['python', '-c', "import sys; sys.stderr.write('ook'); sys.exit(1)"], stderr=subprocess.PIPE)

In [144]: p.stderr.read()
Out[144]: 'ook'

In [145]: p.returncode

In [146]: p.kill()

In [147]: p.returncode

In [148]: 

所以我可以读取 stderr,这意味着我给 subprocess.Popen 的命令正在运行,但我无法获得 subprocess.Popen 的返回码。有什么想法吗?

最佳答案

您必须等待命令完成。

>>> p.wait()
1
>>> p.returncode
1

或者使用communicate:

>>> stdout, stderr = p.communicate()
>>> stdout
>>> stderr
'ook'
>>> p.returncode
1

关于Python subprocess.Popen 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567114/

相关文章:

c - 系统命令的打开和输出

python - 创建一个 Python Pickle 支持的网站有什么问题吗?

python - 使用子进程在没有 sudo 的情况下注销

python - 线程中的线程

python - 当通过子进程启动的应用程序关闭时Python执行操作

Python函数捕获子进程stdout和stderr到日志文件

python - 为什么 `subprocess.Popen` 向 shell 返回不同的输出? - window

python - 无法为 Google Cloud Storage 的网址签名

python - y 轴的最小值未应用于 matplotlib vlines 图中

javascript - 使用网站输入运行 python 脚本