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

(yzsuai) #1

executable program running a script is available as sys.executable. In general, the
process mode flag is taken from these predefined values:


os.P_NOWAIT and os.P_NOWAITO
The spawn functions will return as soon as the new process has been created, with
the process ID as the return value. Available on Unix and Windows.


os.P_WAIT
The spawn functions will not return until the new process has run to completion
and will return the exit code of the process if the run is successful or “-signal” if a
signal kills the process. Available on Unix and Windows.


os.P_DETACH and os.P_OVERLAY
P_DETACH is similar to P_NOWAIT, but the new process is detached from the console
of the calling process. If P_OVERLAY is used, the current program will be replaced
(much like os.exec). Available on Windows.


In fact, there are eight different calls in the spawn family, which all start a program but
vary slightly in their call signatures. In their names, an “l” means you list arguments
individually, “p” means the executable file is looked up on the system path, and “e”
means a dictionary is passed in to provide the shelled environment of the spawned
program: the os.spawnve call, for example, works the same way as os.spawnv but accepts
an extra fourth dictionary argument to specify a different shell environment for the
spawned program (which, by default, inherits all of the parent’s settings):


os.spawnl(mode, path, ...)
os.spawnle(mode, path, ..., env)
os.spawnlp(mode, file, ...) # Unix only
os.spawnlpe(mode, file, ..., env) # Unix only
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args) # Unix only
os.spawnvpe(mode, file, args, env) # Unix only

Because these calls mimic the names and call signatures of the os.exec variants, see
earlier in this chapter for more details on the differences between these call forms.
Unlike the os.exec calls, only half of the os.spawn forms—those without system path
checking (and hence without a “p” in their names)—are currently implemented on
Windows. All the process mode flags are supported on Windows, but detach and
overlay modes are not available on Unix. Because this sort of detail may be prone to
change, to verify which are present, be sure to see the library manual or run a dir built-
in function call on the os module after an import.


Here is the script in Example 5-35 at work on Windows, spawning 10 independent
copies of the child.py Python program we met earlier in this chapter:


C:\...\PP4E\System\Processes> type child.py
import os, sys
print('Hello from child', os.getpid(), sys.argv[1])

C:\...\PP4E\System\Processes> python spawnv.py

260 | Chapter 5: Parallel System Tools

Free download pdf