[英]Get only stderr output from subprocess.check_output
I want to run an external process in python, and process its stderr
only. 我想在python中运行外部进程,并仅处理其stderr
。
I know I can use subprocess.check_output
, but how can I redirect the stdout to /dev/null
(or ignore it in any other way), and receive only the stderr
? 我知道我可以使用subprocess.check_output
,但是如何将stdout重定向到/dev/null
(或以任何其他方式忽略它),并且仅接收stderr
?
Unfortunately you have tagged this python-2.7 , as in python 3.5 and up this would be simple using run()
: 不幸的是,您已经标记了此python-2.7 ,就像在python 3.5中一样,使用run()
可以很简单:
import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
With check_output()
stdout simply cannot be redirected: 使用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.
Use Popen
objects and communicate()
with python versions less than 3.5. 使用Popen
对象并在python版本低于3.5的情况下使用communicate()
。 Open /dev/null
using os.devnull
in python 2.7: 在python 2.7中使用os.devnull
打开/dev/null
:
>>> 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 sends input to stdin, if piped, and reads from stdout and stderr until end-of-file is reached. Communicate将输入发送到stdin(如果已通过管道传输),并从stdout和stderr读取,直到到达文件末尾。
I found a simple trick: 我发现了一个简单的技巧:
import subprocess
stderr_str = subprocess.check_output('command 2>&1 >/dev/null')
This will filter out the stdout, and keeps only the stderr. 这将滤除标准输出,并仅保留标准错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.