Reputation: 9112
I want to run an external process in python, and process its stderr
only.
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
?
Upvotes: 3
Views: 5136
Reputation: 9112
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.
Upvotes: 1
Reputation: 52939
Unfortunately you have tagged this 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
With check_output()
stdout simply cannot be redirected:
>>> 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. Open /dev/null
using os.devnull
in python 2.7:
>>> 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.
Upvotes: 6