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

(yzsuai) #1

redirection utility function, we need to deal in terms of functions, not files). When run
directly, the function reads from the keyboard and writes to the screen, just as if it were
run as a program without redirection:


C:\...\PP4E\System\Streams> python
>>> from teststreams import interact
>>> interact()
Hello stream world
Enter a number> 2
2 squared is 4
Enter a number> 3
3 squared is 9
Enter a number^Z
Bye
>>>

Now, let’s run this function under the control of the redirection function in
redirect.py and pass in some canned input text. In this mode, the interact function
takes its input from the string we pass in ('4\n5\n6\n'—three lines with explicit end-
of-line characters), and the result of running the function is a tuple with its return value
plus a string containing all the text written to the standard output stream:


>>> from redirect import redirect
>>> (result, output) = redirect(interact, (), {}, '4\n5\n6\n')
>>> print(result)
None
>>> output
'Hello stream world\nEnter a number>4 squared is 16\nEnter a number>5 squared
is 25\nEnter a number>6 squared is 36\nEnter a number>Bye\n'

The output is a single, long string containing the concatenation of all text written to
standard output. To make this look better, we can pass it to print or split it up with
the string object’s splitlines method:


>>> for line in output.splitlines(): print(line)
...
Hello stream world
Enter a number>4 squared is 16
Enter a number>5 squared is 25
Enter a number>6 squared is 36
Enter a number>Bye

Better still, we can reuse the more.py module we wrote in the preceding chapter
(Example 2-1); it’s less to type and remember, and it’s already known to work well (the
following, like all cross-directory imports in this book’s examples, assumes that the
directory containing the PP4E root is on your module search path—change your PYTHON
PATH setting as needed):


>>> from PP4E.System.more import more
>>> more(output)
Hello stream world
Enter a number>4 squared is 16
Enter a number>5 squared is 25

Standard Streams | 125
Free download pdf