[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

prints stuff to afile instead of to sys.stdout. The net effect is similar to simply as-
signing sys.stdout to an object, but there is no need to save and restore in order to
return to the original output stream (as shown in the section on redirecting streams to
objects). For example:


import sys
print('spam' * 2, file=sys.stderr)

will send text the standard error stream object rather than sys.stdout for the duration
of this single print call only. The next normal print statement (without file) prints to
standard output as usual. Similarly, we can use either our custom class or the standard
library’s class as the output file with this hook:


>>> from io import StringIO
>>> buff = StringIO()
>>> print(42, file=buff)
>>> print('spam', file=buff)
>>> print(buff.getvalue())
42
spam

>>> from redirect import Output
>>> buff = Output()
>>> print(43, file=buff)
>>> print('eggs', file=buff)
>>> print(buff.text)
43
eggs

Other Redirection Options: os.popen and subprocess Revisited


Near the end of the preceding chapter, we took a first look at the built-in os.popen
function and its subprocess.Popen relative, which provide a way to redirect another
command’s streams from within a Python program. As we saw, these tools can be used
to run a shell command line (a string we would normally type at a DOS or csh prompt)
but also provide a Python file-like object connected to the command’s output stream—
reading the file object allows a script to read another program’s output. I suggested that
these tools may be used to tap into input streams as well.


Because of that, the os.popen and subprocess tools are another way to redirect streams
of spawned programs and are close cousins to some of the techniques we just met.
Their effect is much like the shell | command-line pipe syntax for redirecting streams
to programs (in fact, their names mean “pipe open”), but they are run within a script
and provide a file-like interface to piped streams. They are similar in spirit to the
redirect function, but are based on running programs (not calling functions), and the
command’s streams are processed in the spawning script as files (not tied to class ob-
jects). These tools redirect the streams of a program that a script starts, instead of
redirecting the streams of the script itself.


128 | Chapter 3: Script Execution Context

Free download pdf