>>> result = os.popen('python makewords.py').read()
>>> print(result)
spam
eggs
ham
The equivalent os.spawn calls achieve the same effect, with a slightly more complex call
signature that provides more control over the way the program is launched:
>>> os.spawnv(os.P_WAIT, r'C:\Python31\python', ('python', 'makewords.py'))
spam
eggs
ham
0
>>> os.spawnl(os.P_NOWAIT, r'C:\Python31\python', 'python', 'makewords.py')
1820
>>> spam
eggs
ham
The spawn calls are also much like forking programs in Unix. They don’t actually copy
the calling process (so shared descriptor operations won’t work), but they can be used
to start a program running completely independent of the calling program, even on
Windows. The script in Example 5-35 makes the similarity to Unix programming pat-
terns more obvious. It launches a program with a fork/exec combination on Unix-like
platforms (including Cygwin), or an os.spawnv call on Windows.
Example 5-35. PP4E\System\Processes\spawnv.py
"""
start up 10 copies of child.py running in parallel;
use spawnv to launch a program on Windows (like fork+exec);
P_OVERLAY replaces, P_DETACH makes child stdout go nowhere;
or use portable subprocess or multiprocessing options today!
"""
import os, sys
for i in range(10):
if sys.platform[:3] == 'win':
pypath = sys.executable
os.spawnv(os.P_NOWAIT, pypath, ('python', 'child.py', str(i)))
else:
pid = os.fork()
if pid != 0:
print('Process %d spawned' % pid)
else:
os.execlp('python', 'python', 'child.py', str(i))
print('Main process exiting.')
To make sense of these examples, you have to understand the arguments being passed
to the spawn calls. In this script, we call os.spawnv with a process mode flag, the full
directory path to the Python interpreter, and a tuple of strings representing the shell
command line with which to start a new program. The path to the Python interpreter
Other Ways to Start Programs | 259