PyWhich

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 5 10:56:14 EDT 2011


Billy Mays wrote:

> The reason I used stdout was because I was going to be using it in a
> tool chain where the stdout might need to be formatted for another
> program to read in.

print writes to sys.stdout unless you tell it different.

>>> import sys
>>> import StringIO
>>> capture = StringIO.StringIO()
>>> sys.stdout = capture
>>> print "spam"
>>> sys.stdout = sys.__stdout__  # Restore the real file.
>>> capture.getvalue()
'spam\n'

Syntax for printing elsewhere is ugly as sin in Python 2, but it works:

>>> print >>sys.stderr, "spam"
spam
>>> print >>capture, "ham"
>>> capture.getvalue()
'spam\nham\n'




> Thats also why I was catching ImportError since a 
> later version of this script might need to do something special with it.

Well you better also catch SyntaxError, because a later version of your
script might need to do something special with it too :)

Also RuntimeError, ValueError, TypeError... *wink*


-- 
Steven




More information about the Python-list mailing list