SaltyCrane Blog — Notes on JavaScript and web development

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 os
stdout = os.popen("dir asdkfhqweiory")
print stdout.read()
And your output will be something like:
>>> ================================ RESTART ================================
>>>
Volume in drive C has no label.
Volume Serial Number is XXXXXXXX

Directory of C:\Python25


>>>
If you wanted the error message, popen won't give it to you. To capture both stdout and stderr, use popen4:
import os

(dummy, stdout_and_stderr) = os.popen4("dir asdkfhqweiory")
print stdout_and_stderr.read()
This will give you the following output (which includes the error message):
>>> ================================ RESTART ================================
>>>
Volume in drive C has no label.
Volume Serial Number is XXXXXXXX

Directory of C:\Python25

File Not Found

>>>
See http://docs.python.org/lib/os-newstreams.html for more information.

Comments