Home >Backend Development >Python Tutorial >How to call system commands in Python
This method directly calls the standard C system() function. It only runs the system command in a sub-terminal and cannot obtain the return information after the command execution.
The return value of os.system(cmd). If the execution is successful, 0 will be returned, indicating that the command is executed successfully. Otherwise, it is an execution error.
The return value of using os.system is the exit status code of the script. After calling the shell script, this method returns a 16-bit binary number. The low bit is the signal number to kill the called script, and the high bit is the script. exit status code.
os.system() returns a value of 0 and the linux command returns a value of 0.
os.system() return value is 256, the sixteen-digit binary number is shown as: 00000001, 00000000, the high eight bits are converted to decimal 1, which corresponds to the linux command return value 1.
os.system() return value is 512, the sixteen-digit binary number is shown as: 00000010, 00000000, the high eight bits are converted to decimal 2, which corresponds to the linux command return value 2.
import os result = os.system('cat /etc/passwd') print(result) # 0
The os.popen() method not only executes the command but also returns the information object after execution (often used to obtain the return information after executing the command). It is passed A pipeline file returns the results. What is returned by os.popen() is the object of file read. You can see the output of the execution by reading it with read().
import os result = os.popen('cat /etc/passwd') print(result.read())
import commands status = commands.getstatus('cat /etc/passwd') print(status) output = commands.getoutput('cat /etc/passwd') print(output) (status, output) = commands.getstatusoutput('cat /etc/passwd') print(status, output)
Subprocess is a powerful subprocess management module that replaces os.system, os.spawn*, etc. A module of methods.
When the parameters or returns of the execution command contain Chinese characters, it is recommended to use subprocess.
import subprocess res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # 使用管道 print res.stdout.read() # 标准输出 for line in res.stdout.readlines(): print line res.stdout.close() # 关闭
The above is the detailed content of How to call system commands in Python. For more information, please follow other related articles on the PHP Chinese website!