Python: subprocess library

  • 2021-01-06 00:40:25
  • OfStack


The purpose of using the subprocess module is to replace some older modules and methods such as os.system.

When we run python, we are creating and running a process. As with Linux, a process can fork1 child process and make the child process exec another program. In Python, we use the subprocess package from the standard library to subprocess fork1 and run an external program.

The ES20en package defines several child process creation functions, each of which creates child processes in a different way, so we can use one of them as needed. In addition, subprocess provides some tools for managing standard streams (standard stream) and pipes (pipe) to use text communication between processes.

The import module

>>> import subprocess

Command call()

Execute the command provided by the argument, running the command with the array as the argument. Its function is similar to os.system(cmd).


The parameter shell defaults to False.

When shell is set to True, it is possible to directly pass a string:

>>>'ls -l',shell=True)

Returns the result check_output()

check_ouput() : check_ouput(); check_ouput() : check_ouput();

>>> result = subprocess.check_output(['ls','-l'],shell=True)
>>> result.decode('utf-8')

The process creates and manages the Popen class

subprocess.popen replaces os.popen. An Popen class can be created to create processes and complex interactions.

Create a child process that does not wait

import subprocess

child = subprocess.Popen(['ping','-c','4',''])

Add child process wait

import subprocess

child = subprocess.Popen(['ping','-c','4',''])
child.wait() #  Wait for the child process to finish 

With the addition of wait(), the main process waits for the child process to finish before executing the following statement.

Subprocess text flow control

Standard output redirection:

import subprocess

child = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE)    # Directs the standard output to subprocess.PIPE

Use stdin in conjunction with it:

import subprocess

child1 = subprocess.Popen(['cat','/etc/passwd'],stdout=subprocess.PIPE)
child2 = subprocess.Popen(['grep','root'],stdin=child1.stdout,stdout=subprocess.PIPE)

print child2.communicate()

Related articles: