Home > Article > Backend Development > Introduction to the usage of subprocess library in Python
This article brings you an introduction to the usage of the subprocess library in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction
The purpose of using the subprocess module is to replace some old modules and methods such as os.system.
Import module
>>> import subprocess
Command execution call()
Execute the command provided by the parameter and run the array as a parameter Order. Its function is similar to os.system(cmd).
>>> subprocess.call(['ls','-l')
The shell parameter defaults to False.
When the shell is set to True, you can directly pass the string:
>>> subprocess.call('ls -l',shell=True)
Get the return result check_output()
call() does not return the displayed result Yes, you can use check_ouput() to get the returned results:
>>> result = subprocess.check_output(['ls','-l'],shell=True) >>> result.decode('utf-8')
Process Creation and Management Popen Class
subprocess.popen instead of os.popen. A Popen class can be created to create processes and perform complex interactions.
Create a child process that does not wait
import subprocess child = subprocess.Popen(['ping','-c','4','www.baidu.com']) print('Finished')
Add a child process to wait
import subprocess child = subprocess.Popen(['ping','-c','4','www.baidu.com']) child.wait() # 等待子进程结束 print('Finished')
After adding wait(), the main The process will wait for the child process to end before executing the following statement.
Subprocess text flow control
Standard output redirection:
import subprocess child = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE) #将标准输出定向输出到subprocess.PIPE print(child.stdout.read())
Use stdin to work 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()
The above is the detailed content of Introduction to the usage of subprocess library in Python. For more information, please follow other related articles on the PHP Chinese website!