Detailed Explanation of subprocess Example Usage and Knowledge Points in python

  • 2021-12-05 06:33:14
  • OfStack

1, subprocess this module to generate sub-process, and can be connected to the standard input, output, error of sub-process, can also get the return value of sub-process.

2. subprocess provides two methods to call subroutines.

Instances


# coding:utf-8
import os
# popen Returns a file object, the same as open Operation 1 Sample 
f = os.popen(r"ls", "r")
l = f.read()
print(l)
f.close()

Python subprocess Knowledge Point Extension

The subprocess module is used to replace older modules and methods such as os. system.

When we run python, we are all creating and running a process. Like the Linux process, one process can be an fork1 child process, and let this child process exec another program. In Python, we use the subprocess package in the standard library to get the fork1 sub-process and run an external program.

subprocess package has several functions to create sub-processes, which create sub-processes in different ways, so we can choose one to use according to our needs. In addition, subprocess provides tools for managing standard streams (standard stream) and pipes (pipe) to use text communication between processes.

Import module


>>> import subprocess

Command to execute call ()

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


>>> subprocess.call(['ls','-l')

Where the parameter shell defaults to False.

When shell is set to True, you can pass a string directly:


>>> subprocess.call('ls -l',shell=True)

Get the return result check_output ()

call () does not return the displayed results, and you can use check_ouput () to get the returned results:


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

Processes create and manage Popen classes

subprocess. popen replaces os. popen. You can create an Popen class to create processes and perform complex interactions.

Create a child process without waiting


import subprocess

child = subprocess.Popen(['ping','-c','4','www.baidu.com'])
print('Finished')

Add child process wait


import subprocess

child = subprocess.Popen(['ping','-c','4','www.baidu.com'])
child.wait() #  Wait for the child process to end 
print('Finished')

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

Child process text flow control

Standard output redirection:


import subprocess

child = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE)      # Directed output of standard output to subprocess.PIPE
print(child.stdout.read()) 

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: