Os.system
Os.spawn
Os.popen
Popen2
Commands
All these things will be replaced by subprocess, subprocess really good, there is no!
1, Subprocess.call ()
The Subprocess.call () parameter is a list that needs to be added shell=true if you want the shell command to be passed in as a string.
>>> from subprocess import call>>> call ("Df-h", shell=true) Filesystem Size used Avail use% mounted On/dev/disk1 112G 75G 38G 67%/
0
If you do not specify Shell=true, you need to pass a list as a parameter
>>> call ([' DF ', '-h ']) Filesystem Size used Avail use% mounted on/dev/disk1 112G 75G 38G 67%/
0
The return value is the Shell's ReturnCode
2, subprocess. Popen ()
The call method is an encapsulation of popen, and the return value of call is the exit code of the shell, and Popen returns a Popen object. It is convenient to use, but it is blocked and will wait until the call method is finished to continue execution. Popen is non-blocking, equivalent to put in the background execution, if you need to get the standard shell command output, error output, with Popen more convenient.
>>> from subprocess import popen,pipe>>> pobj = Popen (' ls-l ', stdout=subprocess. Pipe,stderr=subprocess. pipe,shell=true) >>> result = Pobj.communicate ()
Result is returned as a list, result[0] is the standard output, result[1] is the error output
>>> ExitCode = Pobj.poll () >>> print ExitCode
2
Call the poll method of the Popen object to return the shell exit code
Here is a method of encapsulation, the argument is the command to be passed, if you do not add shell=true, you need to pass the command as a list, otherwise, pass a string. function returns a list of standard outputs, error outputs, and ReturnCode
From subprocess Import Popen,pipe
def execcommand (commandstr): Process = Popen (commandstr,stdout=pipe,stderr=pipe,shell=true) res = Process.communicat E () toout = res[0] Toerr = res[1] ExitCode = process.poll () result = [Toout,toerr,exitcode] return result
This article is from the "Candle Shadow Red" blog, be sure to keep this source http://gccmx.blog.51cto.com/479381/1611595
Python calls system commands