How to use python and popen4 to capture stdout and stderr from a command



This is my OLD blog. I've copied this post over to my NEW blog at:

http://www.saltycrane.com/blog/2007/03/how-to-use-python-and-popen4-to-capture_12/

You should be redirected in 2 seconds.



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.

No comments:

About

This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

http://www.saltycrane.com/blog/.

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.