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

(yzsuai) #1
Hello from child −583587 0
Hello from child −558199 2
Hello from child −586755 1
Hello from child −562171 3
Main process exiting.
Hello from child −581867 6
Hello from child −588651 5
Hello from child −568247 4
Hello from child −563527 7
Hello from child −543163 9
Hello from child −587083 8

Notice that the copies print their output in random order, and the parent program exits
before all children do; all of these programs are really running in parallel on Windows.
Also observe that the child program’s output shows up in the console box where
spawnv.py was run; when using P_NOWAIT, standard output comes to the parent’s con-
sole, but it seems to go nowhere when using P_DETACH (which is most likely a feature
when spawning GUI programs).


But having shown you this call, I need to again point out that both the subprocess and
multiprocessing modules offer more portable alternatives for spawning programs with
command lines today. In fact, unless os.spawn calls provide unique behavior you can’t
live without (e.g., control of shell window pop ups on Windows), the platform-specific
alternatives code of Example 5-35 can be replaced altogether with the portable multi
processing code in Example 5-33.


The os.startfile call on Windows


Although os.spawn calls may be largely superfluous today, there are other tools that
can still make a strong case for themselves. For instance, the os.system call can be used
on Windows to launch a DOS start command, which opens (i.e., runs) a file inde-
pendently based on its Windows filename associations, as though it were clicked.
os.startfile makes this even simpler in recent Python releases, and it can avoid block-
ing its caller, unlike some other tools.


Using the DOS start command


To understand why, first you need to know how the DOS start command works in
general. Roughly, a DOS command line of the form start command works as if command
were typed in the Windows Run dialog box available in the Start button menu. If
command is a filename, it is opened exactly as if its name was double-clicked in the
Windows Explorer file selector GUI.


For instance, the following three DOS commands automatically start Internet Explorer,
my registered image viewer program, and my sound media player program on the files
named in the commands. Windows simply opens the file with whatever program is
associated to handle filenames of that form. Moreover, all three of these programs run
independently of the DOS console box where the command is typed:


Other Ways to Start Programs | 261
Free download pdf