12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The print >> file ExtensionThis trick of redirecting printed text by assigning sys.stdout is very commonly usedin practice. But one potential problem with the last section’s code is that there is nodirect way to restore the original output stream should you need to switch back afterprinting to a file. Because sys.stdout is just a normal file object, you can always saveit and restore it if needed: *>>> import sys>>> temp = sys.stdout # Save for restoring later>>> sys.stdout = open('log.txt', 'a') # Redirect prints to a file>>> print 'spam' # Prints go to file, not here>>> print 1, 2, 3>>> sys.stdout.close( ) # Flush output to disk>>> sys.stdout = temp # Restore original stream>>> print 'back here' # Prints show up here againback here>>> print open('log.txt').read( ) # Result of earlier printsspam1 2 3This need crops up fairly regularly, and this manual saving and restoring of the originaloutput stream is just complicated enough that a print extension was added tomake it unnecessary. When a print statement begins with a >> followed by an outputfile (or other) object, that single print statement sends its text to the object’swrite method, but it does not reset sys.stdout. Because the redirection is temporary,normal print statements keep printing to the original output stream:log = open('log.txt', 'a')print >> log, x, y, zprint a, b, c# Print to a file-like object# Print to original stdoutThe >> form of print is handy if you need to print to both files and the standard outputstream in the same program. If you use this form, however, be sure to give it afile object (or an object that has the same write method as a file object), not a file’sname string:>>> log = open('log.txt', 'w')>>> print >> log, 1, 2, 3>>> print >> log, 4, 5, 6>>> log.close( )>>> print 7, 8, 97 8 9>>> print open('log.txt').read( )1 2 34 5 6* You can also use the relatively new _ _stdout_ _ attribute in the sys module, which refers to the original valuesys.stdout had at program startup time. You still need to restore sys.stdout to sys._ _stdout_ _ to go backto this original stream value, though. See the sys module in the library manual for more details.232 | Chapter 11: Assignment, Expressions, and print

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!