Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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.

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode