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
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(5)
-
aws
(9)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(13)
-
conkeror
(2)
-
core
(2)
-
cygwin
(17)
-
datastructures
(14)
-
datetime
(4)
-
decorators
(4)
-
django
(40)
-
emacs
(22)
-
files_directories
(11)
-
git
(5)
-
hardware
(5)
-
install_setup
(8)
-
javascript
(3)
-
keyboard
(9)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
persistence
(5)
-
preferences
(7)
-
processes
(4)
-
pyqt
(18)
-
python
(144)
-
ratpoison
(3)
-
regexes
(6)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(14)
-
ssh
(10)
-
subversion
(6)
-
twisted
(7)
-
ubuntu
(65)
-
urxvt
(5)
-
vxworks
(25)
-
webdev
(5)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Marty Alchin
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan