仅从 subprocess.check_output 获取 stderr 输出
Get only stderr output from subprocess.check_output
我想在 python 中 运行 一个外部进程,并且只处理它的 stderr
。
我知道我可以使用 subprocess.check_output
,但我怎样才能将标准输出重定向到 /dev/null
(或以任何其他方式忽略它),并且只接收 stderr
?
很遗憾,您已标记此 python-2.7, as in python 3.5 and up this would be simple using run()
:
import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
使用 check_output()
stdout 根本无法重定向:
>>> 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.
在python 2.7:
中使用Popen
objects and communicate()
with python versions less than 3.5. Open /dev/null
using 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
Communicate 将输入发送到 stdin(如果通过管道传输),并从 stdout 和 stderr 读取直到到达文件末尾。
我发现了一个简单的技巧:
import subprocess
stderr_str = subprocess.check_output('command 2>&1 >/dev/null')
这将过滤掉标准输出,只保留标准错误。
我想在 python 中 运行 一个外部进程,并且只处理它的 stderr
。
我知道我可以使用 subprocess.check_output
,但我怎样才能将标准输出重定向到 /dev/null
(或以任何其他方式忽略它),并且只接收 stderr
?
很遗憾,您已标记此 python-2.7, as in python 3.5 and up this would be simple using run()
:
import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
使用 check_output()
stdout 根本无法重定向:
>>> 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.
在python 2.7:
中使用Popen
objects and communicate()
with python versions less than 3.5. Open /dev/null
using 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
Communicate 将输入发送到 stdin(如果通过管道传输),并从 stdout 和 stderr 读取直到到达文件末尾。
我发现了一个简单的技巧:
import subprocess
stderr_str = subprocess.check_output('command 2>&1 >/dev/null')
这将过滤掉标准输出,只保留标准错误。