Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between subprocess.Popen and os.system

People also ask

What is OS Popen?

The os. popen method opens a pipe from a command. This pipe allows the command to send its output to another command. The output is an open file that can be accessed by other programs. The syntax is as follows: os.popen(command[, mode[, bufsize]])

Is OS Popen deprecated?

popen is not really deprecated; There is an error in the standard library and os.

What is OS system in Python?

The OS module in python provides functions for interacting with the operating system. OS, comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. os. system() method execute the command (a string) in a subshell.

Is OS system deprecated?

os. system function has been deprecated. In other words, this function has been replaced. The subprocess module serves as a replacement to this and Python officially recommends using subprocess for shell commands.


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().


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


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.


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