Running Other Programs
The os
module
offers several ways for your program to run other programs. The
simplest way to run another program is through function
os.system
, although this offers no way to control
the external program. The os
module also provides
a number of functions whose names start with exec
.
These functions offer fine-grained control. A program run by one of
the exec
functions, however, replaces the current
program (i.e., the Python interpreter) in the same process. In
practice, therefore, you use the exec
functions
mostly on platforms that let a process duplicate itself by
fork
(i.e., Unix-like platforms). Finally,
os
functions whose names start with
spawn
and popen
offer
intermediate simplicity and power: they are cross-platform and not
quite as simple as system
, but simple and usable
enough for most purposes.
The exec
and spawn
functions
run a specified executable file given the executable
file’s path, arguments to pass to it, and optionally
an environment mapping. The system
and
popen
functions execute a command, a string passed
to a new instance of the platform’s default shell
(typically /bin/sh
on Unix,
command.com
or cmd.exe
on
Windows). A command is a more general concept than an executable
file, as it can include shell functionality (pipes, redirection,
built-in shell commands) using the normal shell syntax specific to
the current platform.
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.