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

(yzsuai) #1

We can get close to this with os.popen, but that the fact that its pipes are read or write
(and not both) prevents us from catching the second script’s output in our code:


>>> import os
>>> p1 = os.popen('python writer.py', 'r')
>>> p2 = os.popen('python reader.py', 'w')
>>> p2.write( p1.read() )
36
>>> X = p2.close()
Got this: "Help! Help! I'm being repressed!"
The meaning of life is 42 84
>>> print(X)
None

From the broader perspective, the os.popen call and subprocess module are Python’s
portable equivalents of Unix-like shell syntax for redirecting the streams of spawned
programs. The Python versions also work on Windows, though, and are the most
platform-neutral way to launch another program from a Python script. The command-
line strings you pass to them may vary per platform (e.g., a directory listing requires an
ls on Unix but a dir on Windows), but the call itself works on all major Python
platforms.


On Unix-like platforms, the combination of the calls os.fork, os.pipe, os.dup, and
some os.exec variants can also be used to start a new independent program with
streams connected to the parent program’s streams. As such, it’s yet another way to
redirect streams and a low-level equivalent to tools such as os.popen (os.fork is available
in Cygwin’s Python on Windows).


Since these are all more advanced parallel processing tools, though, we’ll defer further
details on this front until Chapter 5, especially its coverage of pipes and exit status
codes. And we’ll resurrect subprocess again in Chapter 6, to code a regression tester
that intercepts all three standard streams of spawned test scripts—inputs, outputs, and
errors.


But first, Chapter 4 continues our survey of Python system interfaces by exploring the
tools available for processing files and directories. Although we’ll be shifting focus
somewhat, we’ll find that some of what we’ve learned here will already begin to come
in handy as general system-related tools. Spawning shell commands, for instance, pro-
vides ways to inspect directories, and the file interface we will expand on in the next
chapter is at the heart of the stream processing techniques we have studied here.


132 | Chapter 3: Script Execution Context

Free download pdf