Python subprocess.popen() Tutorial

Python provides the subprocess module in order to create and manage processes. The subprocess.popen() is one of the most useful methods which is used to create a process. This process can be used to run a command or execute binary. The process creation is also called as spawning a new process which is different from the current process.

subprocess.Popen() Syntax

The subprocess module Popen() method syntax is like below.

subprocess.Popen(COMMAND,STDIN, STDOUT,STDERR,SHELL)
  • COMMAND is a string or a list which contains the command or binary with its parameters and options.
  • STDIN is the standard input which is optional.
  • STDOUT is the standard output which is optional.
  • STDERR is the standard error which is optional.
  • SHELL is used to run specified process in the shell where shell environment is used.

Create Process

The Popen() method can be used to create a process easily. As stated previously the Popen() method can be used to create a process from a command, script, or binary. In the following example, we create a process using the ls command.

import subprocess

subprocess.Popen("ls -al",shell=True)

Provide Command Name and Parameters As List

The Popen() method can accept the command/binary/script name and parameter as a list that is more structured and easy to read way. The command/binary/script name is provided as the first item of the list and other parameters can be added as a single item or multiple items. In the following example, we run the ls command with -la parameters.

import subprocess

subprocess.Popen(["ls","-al"])

Call Popen() Method Directly

The Popen() method is provided via the subprocess module. This method can be called directly without using the subprocess module by importing the Popen() method.

from subprocess impor Popen

Popen(["ls","-al"])

Read Standard Output

Every command execution provides non or some output. The Popen() process execution can provide some output which can be read with the communicate() method of the created process.

from subprocess impor Popen,PIPE

p = Popen(["ls","-al"],stdout=PIPE)

stderr = p.communicate()

Read Standard Error

Also the standard error output can be read by using the stderr parameter setting it as PIPE and then using the communicate() method like below.

from subprocess impor Popen,PIPE

p = Popen(["ls","-al"],stderr=PIPE)

stderr = p.communicate()

Leave a Comment