Dev*_*ark 3 python subprocess stderr python-2.7
我想在 python 中运行一个外部进程,并stderr只处理它。
我知道我可以使用subprocess.check_output,但是如何将标准输出重定向到/dev/null(或以任何其他方式忽略它),并且只接收stderr?
不幸的是,你已经标记了这个python-2.7,就像在 python 3.5 及更高版本中一样,这很容易使用run():
import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
Run Code Online (Sandbox Code Playgroud)
使用check_output()标准输出根本无法重定向:
>>> subprocess.check_output(('ls', 'asdfqwer'), stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
raise ValueError('stdout argument not allowed, it will be overridden.')
ValueError: stdout argument not allowed, it will be overridden.
Run Code Online (Sandbox Code Playgroud)
使用Popen对象和communicate()低于 3.5 的 Python 版本。在python 2.7中打开/dev/null使用os.devnull:
>>> import subprocess
>>> import os
>>> with open(os.devnull, 'wb') as devnull:
... proc = subprocess.Popen(('ls', 'asdfqwer'),
... stdout=devnull,
... stderr=subprocess.PIPE)
... proc.communicate()
... proc.returncode
...
(None, "ls: cannot access 'asdfqwer': No such file or directory\n")
2
Run Code Online (Sandbox Code Playgroud)
Communicate 将输入发送到 stdin(如果通过管道传输),并从 stdout 和 stderr 读取,直到到达文件结尾。