Several Methods for python to execute shell commands
1. OS. system ()
Advantages: it is simple and can be used on linux and widnows platforms. You only need to determine whether the returned result is 0 or 1 to determine whether the execution is successful.
Disadvantage: The returned output cannot be obtained.
Example:
os.system('ls')
2. OS. popen ()
Advantage: output results can be obtained.
Disadvantage: The execution result cannot be obtained. It must be determined and processed based on the output result.
Example:
output = os.popen('ls')print output.read()
3. commands. getstatusoutput ()
Advantage: the execution results and returned results can be obtained at the same time.
Disadvantage: windows platform does not support
Example:
status, output = commands.getstatusoutput('dir')print status, output
4. subprocess. Popen ()
Advantage: the execution result and returned result can be obtained at the same time, and the linux and windows platforms are supported.
Example:
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)msg = ''for line in p.stdout.readlines(): msg += linestatus = p.wait()output = msg