There are several common ways to execute system commands in Python
Note: The following example code runs under Python3.5.
os.system(cmd)
Run the system command in the sub-terminal to get the return information after the command execution and the status returned by the execution
>>> import os >>> os.system('date') 2018年 4月 8日 星期日 19时29分13秒 CST 0 #运行状态号,0表示正确
After execution, two lines of results are returned. The first line is the result, and the second line is the execution status information
os.popen(cmd)
Not only executes the command but also returns the information object after execution (often used to obtain the return information after executing the command). The result is returned through a pipeline file
>>> import os >>> nowtime = os.popen('date') >>> print(nowtime.read()) 2018年 4月 8日 星期日 19时30分35秒 CST
Method Description
getoutput Gets the return information after executing the command
getstatus gets the status value of the executed command (if the command is executed successfully, it returns a value of 0, otherwise it returns non-0)
getstatusoutput Gets the status value and return information of the executed command
>>> import commonds >>> status, output = commands.getstatusoutput('date') >>> print(status) # 0 >>> print(output) # 2018年 4月 8日 星期日 19时31分45秒 CST
Note 1: The return value (status) returned by using this method under a Unix-like system is not the same as the return value after the script or command is executed. This is because os.wait() is called. The specific reason must be discussed. Learn about the implementation of system wait(). If you need the correct return value (status), you only need to right-shift the return value by 8 bits.
Note 2: When the parameters or returns of the execution command contain Chinese characters, it is recommended to use subprocess.
Use the control and monitoring of threads and assign the returned result to a variable to facilitate program processing. There are rich parameters that can be configured, many options for customization, and high flexibility. When I used os.system before, I encountered the problem of file descriptors being inherited by child processes. I later solved it by using the close_fds = False parameter. Official document: http://python.usyiyi.cn/python_278/library/subprocess.html
>>> import subprocess >>> nowtime = subprocess.Popen('date', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) >>> print(nowtime.stdout.read()) 2018年 4月 8日 星期日 19时32分41秒 CST
The above is the detailed content of Four ways to execute python system commands. For more information, please follow other related articles on the PHP Chinese website!