Reading the error stream from os.popen()

Donn Cave donn at u.washington.edu
Thu Oct 19 13:21:18 EDT 2000


Quoth jmcbray at carcosa.net (Jason F. McBrayer):
| >>>>> "CG" == Carsten Gaebler <cg at schlund.de> writes:
| >>>>> "TAJ" == Tov Are Jacobsen wrote:
|
| TAJ> The msgfmt command below outputs info to the stderr stream,
| TAJ> but the read() method retrieves data from stdin.
|
| TAJ> s = os.popen('/usr/bin/msgfmt  --statistics '+x[0]+'.po').read()
|
| CG> Redirect stderr to stdout:
| CG> s = os.popen('/usr/bin/msgfmt  --statistics '+x[0]+'.po' 2>&1).read()
|
| Or better, use the popen2 module.
|
| import popen2
|
| out, in, err = popen2.popen3('/usr/bin/msgfmt --statistics ' + x[0] + '.po')
| s = err.read()
| del out; del in; del err;

Maybe, assuming this particular command reliably does NOT produce
a lot of output.  Try this:

 out, in, err = popen2.popen3('cat large_file')
 s = err.read()
 ... hang forever.  What's going on here?  cat wants to write all its
output before it closes its error unit, you want to wait for something
on that error stream before you attend to the output;  cat fills up its
output pipe and blocks, and we have a deadlock.

It's often not an issue, but the more different streams you're trying
to deal with for a single source, the more vulnerable to deadlocks.
When the application really just wants all the output and doesn't need
to separate diagnostic output from normal output, "2>&1" is perfect.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list