Online Book Reader

Home Category

Learning Python - Mark Lutz [179]

By Root 1924 0
longer:

import sys

sys.stdout.write(str(X) + ' ' + str(Y) + '\n')

which manually performs a string conversion with str, adds a separator and newline with +, and calls the output stream’s write method. Which would you rather code? (He says, hoping to underscore the programmer-friendly nature of prints....)

Obviously, the long form isn’t all that useful for printing by itself. However, it is useful to know that this is exactly what print operations do because it is possible to reassign sys.stdout to something different from the standard output stream. In other words, this equivalence provides a way of making your print operations send their text to other places. For example:

import sys

sys.stdout = open('log.txt', 'a') # Redirects prints to a file

...

print(x, y, x) # Shows up in log.txt

Here, we reset sys.stdout to a manually opened file named log.txt, located in the script’s working directory and opened in append mode (so we add to its current content). After the reset, every print operation anywhere in the program will write its text to the end of the file log.txt instead of to the original output stream. The print operations are happy to keep calling sys.stdout’s write method, no matter what sys.stdout happens to refer to. Because there is just one sys module in your process, assigning sys.stdout this way will redirect every print anywhere in your program.

In fact, as this chapter’s upcoming sidebar about print and stdout will explain, you can even reset sys.stdout to an object that isn’t a file at all, as long as it has the expected interface: a method named write to receive the printed text string argument. When that object is a class, printed text can be routed and processed arbitrarily per a write method you code yourself.

This trick of resetting the output stream is primarily useful for programs originally coded with print statements. If you know that output should go to a file to begin with, you can always call file write methods instead. To redirect the output of a print-based program, though, resetting sys.stdout provides a convenient alternative to changing every print statement or using system shell-based redirection syntax.

Automatic stream redirection

This technique of redirecting printed text by assigning sys.stdout is commonly used in practice. One potential problem with the last section’s code, though, is that there is no direct way to restore the original output stream should you need to switch back after printing to a file. Because sys.stdout is just a normal file object, you can always save it and restore it if needed:[30]

C:\misc> c:\python30\python

>>> 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 again

back here

>>> print(open('log.txt').read()) # Result of earlier prints

spam

1 2 3

As you can see, though, manual saving and restoring of the original output stream like this involves quite a bit of extra work. Because this crops up fairly often, a print extension is available to make it unnecessary.

In 3.0, the file keyword allows a single print call to send its text to a file’s write method, without actually resetting sys.stdout. Because the redirection is temporary, normal print calls keep printing to the original output stream. In 2.6, a print statement that begins with a >> followed by an output file object (or other compatible object) has the same effect. For example, the following again sends printed text to a file named log.txt:

log = open('log.txt', 'a') # 3.0

print(x, y, z, file=log) # Print to a file-like object

print(a, b, c) # Print to original stdout

log = open('log.txt', 'a') # 2.6

print >> log, x, y, z # Print to a file-like object

print a, b, c # Print to original stdout

These redirected forms of print are handy if you need to print to both files and

Return Main Page Previous Page Next Page

®Online Book Reader