os.system
The system method creates a child process to run an external program, and the method only returns the results of the external program. This method is more suitable for situations where the external program has no output results.
import os
os.system('ls')
commands.getstatusoutput
Use the getoutput method of the commands module. The difference between this method and popend is that popen returns a file handle, while this method returns the output result of an external program as a string, which is more convenient in many cases.
Main method:
This method is very useful when you need to get the output result of an external program. For example, when using urllib to call Web API, you need to process the obtained data. os.popen(cmd) To get the output of the command, just call read() or readlines() again, such as a=os.popen(cmd).read()
import os
ls = os.popen('ls')
print ls.read()
commands.getstatusoutput
Use the getoutput method of the commands module. The difference between this method and popend is that popen returns a file handle, while this method returns the output result of an external program as a string, which is more convenient in many cases.
Main method:
import commands
commands.getstatusoutput('ls -lt') #return(status, output)
subprocess.call
According to the official Python documentation, the subprocess module is used to replace these modules. There is a parallel ssh tool implemented in Python-mssh, the code is very short, but very interesting, it calls subprocess in the thread to start the child process to work.
from subprocess import call
call(["ls","-l"])
import shlex, subprocess
def shell_command(cmd, timeout):
data ={"rc":False,"timeout":False,"stdout":"","stderr":""}try:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)try:
outs, errs = process.communicate(timeout=timeout)
data["stdout"]= outs.decode("utf-8")
data["stderr"]= errs.decode("utf-8")
data["rc"]= True
except subprocess.TimeoutExpired :
process.kill()
outs, errs = process.communicate()
data["rc"]= False
data["stdout"]= outs.decode("utf-8")
data["stderr"]="timeout"
data["timeout"]= True
except Exception as e :
data["rc"]= False
data["stderr"]= e
finally:return data
So far this article on the knowledge points of shell execution in python is introduced. For more related python shell execution content, please search for previous articles on ZaLou.Cn or continue to browse related articles below. Hope you will support ZaLou.Cn more in the future!
Recommended Posts