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

(yzsuai) #1
Unfortunately, beyond this brief introduction, we don’t have space for a more complete
treatment of this module in this book. For more details, refer to the Python library
manual. Here, we turn next to a handful of additional program launching tools and a
wrap up of this chapter.

Other Ways to Start Programs


We’ve seen a variety of ways to launch programs in this book so far—from the os.fork/
exec combination on Unix, to portable shell command-line launchers like os.system,
os.popen, and subprocess, to the portable multiprocessing module options of the last
section. There are still other ways to start programs in the Python standard library,
some of which are more platform neutral or obscure than others. This section wraps
up this chapter with a quick tour through this set.

The os.spawn Calls


The os.spawnv and os.spawnve calls were originally introduced to launch programs on
Windows, much like a fork/exec c a l l c o m b i n a t i o n o n U n i x - l i k e p l a t f o r m s. T o d a y , t h e s e
calls work on both Windows and Unix-like systems, and additional variants have been
added to parrot os.exec.
In recent versions of Python, the portable subprocess module has started to supersede
these calls. In fact, Python’s library manual includes a note stating that this module has
more powerful and equivalent tools and should be preferred to os.spawn calls. More-
over, the newer multiprocessing module can achieve similarly portable results today
when combined with os.exec calls, as we saw earlier. Still, the os.spawn calls continue
to work as advertised and may appear in Python code you encounter.
The os.spawn family of calls execute a program named by a command line in a new
process, on both Windows and Unix-like systems. In basic operation, they are similar
to the fork/exec call combination on Unix and can be used as alternatives to the
system a n d popen c a l l s w e ’ v e a l r e a d y l e a r n e d. I n t h e f o l l o w i n g i n t e r a c t i o n , f o r i n s t a n c e ,
we start a Python program with a command line in two traditional ways (the second
also reads its output):
C:\...\PP4E\System\Processes> python
>>> print(open('makewords.py').read())
print('spam')
print('eggs')
print('ham')

>>> import os
>>> os.system('python makewords.py')
spam
eggs
ham
0

258 | Chapter 5: Parallel System Tools

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf