How to use python and popen4 to capture stdout and stderr from a command
You can use popen to capture stdout from a command:
import osAnd your output will be something like:
stdout = os.popen("dir asdkfhqweiory")
print stdout.read()
>>> ================================ RESTART ================================If you wanted the error message, popen won't give it to you. To capture both stdout and stderr, use popen4:
>>>
Volume in drive C has no label.
Volume Serial Number is XXXXXXXX
Directory of C:\Python25
>>>
import osThis will give you the following output (which includes the error message):
(dummy, stdout_and_stderr) = os.popen4("dir asdkfhqweiory")
print stdout_and_stderr.read()
>>> ================================ RESTART ================================See http://docs.python.org/lib/os-newstreams.html for more information.
>>>
Volume in drive C has no label.
Volume Serial Number is XXXXXXXX
Directory of C:\Python25
File Not Found
>>>
Related posts
- How to use the bash shell with Python's subprocess module instead of /bin/sh — posted 2011-04-13
- How to capture stdout in real-time with Python — posted 2009-10-12
- How to get stdout and stderr using Python's subprocess module — posted 2008-09-23