The Python Oracle

Difference between subprocess.Popen and os.system

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC G Dvoks String Quartet No 12 Ame 2

--

Chapters
00:00 Question
00:19 Accepted answer (Score 153)
01:12 Answer 2 (Score 78)
01:26 Answer 3 (Score 37)
02:21 Answer 4 (Score 26)
02:43 Thank you

--

Full question
https://stackoverflow.com/questions/4813...

Accepted answer links:
[subprocess section of the Python docs]: http://docs.python.org/library/subproces...

Answer 3 links:
[system]: http://linux.die.net/man/3/system
[Unix Popen]: http://linux.die.net/man/3/popen

Answer 4 links:
[PEP here]: http://www.python.org/dev/peps/pep-0324/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #subprocess #system

#avk47



ACCEPTED ANSWER

Score 166


If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

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 flexible os.system().




ANSWER 2

Score 84


subprocess.Popen() is strict super-set of os.system().




ANSWER 3

Score 41


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.

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed

Whereas:

The popen() function opens a process by creating a pipe, forking, and invoking the shell.

If you are thinking which one to use, then use subprocess definitely because you have all the facilities for execution, plus additional control over the process.




ANSWER 4

Score 26


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:

  • using pipe in the shell
  • better newline support
  • better handling of exceptions