What is the difference between subprocess.Popen()
and os.system()
?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
os.system is equivalent to Unix system command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.
where as
If you are thinking, which one to use, then use subprocess definitely because you you have all facilities for execution, plus additional control over the process.
Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:
When running python (cpython) on windows the
<built-in function system>
os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.
That said, an important piece of advice comes from os.system docs, which says:
If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace
os.system()
withsubprocess.Popen()
:...does the same thing as...
The "improved" code looks more complicated, but it's better because once you know
subprocess.Popen()
, you don't need anything else.subprocess.Popen()
replaces several other tools (os.system()
is just one of those) that were scattered throughout three other Python modules.If it helps, think of
subprocess.Popen()
as a very flexibleos.system()
.subprocess.Popen()
is strict super-set ofos.system()
.