Subprocess
The relevant modules and functions that can execute shell commands are:
Os.system
Os.spawn
Os.popen --waste
popen2.*--Waste
commands.*-Discarded, removed in 3.x
import commandsresult = commands.getoutput(‘cmd‘) #
Returns only the result of execution, ignoring the return value. result = commands.getstatus(‘cmd‘)
#
Returns the result of the Ls-ld file execution.result = commands.getstatusoutput(‘cmd‘)
#
Executes command cmd with Os.popen () and returns the tuple (status, result) of two elements. CMD executes in the same way as {cmd;} 2>&1, so that the return result contains standard output and standard errors. Example
>>> subprocess.getstatusoutput (' pwd ')
(0, '/home/ronny ')
>>> subprocess.getoutput (' pwd ')
'/home/ronny '
>>> subprocess.getstatus (' pwd ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror:module ' subprocess ' has no attribute ' GetStatus '
The functions of the relevant modules and functions for executing shell commands are implemented in the Subprocess module and provide richer functionality.
(1) Call
Execute command, return status code (command normal execution returns 0, error returns 1)
ret1=subprocess.call("ifconfig")ret2=subprocess.call("ipconfig") #python3.5不是这样,依然会抛出异常导致无法对ret2赋值print(ret1) #0print(ret2) #1ret = subprocess.call(["ls", "-l"], shell=False) #shell为False的时候命令必须分开写ret = subprocess.call("ls -l", shell=True)
(2) Check_call
Executes the command, returns a status code of 0 if successful execution, or throws an exception
subprocess.check_call(["ls", "-l"])subprocess.check_call("exit 1", shell=True)
(3) Check_output
Executes the command, returns the execution result if the execution succeeds, or throws the exception
subprocess.check_output(["echo", "Hello World!"])subprocess.check_output("exit 1", shell=True)
(4) subprocess. Popen (...)
Used to perform complex system commands
Parameters |
Notes |
Args |
Shell command, which can be a string or sequence type (for example: list, tuple) |
BufSize |
Specifies the buffer. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering |
stdin, stdout, stderr |
Represents the standard input, output, and error handles of the program, respectively |
Preexec_fn |
Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run |
Close_sfs |
Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process. Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process. |
Shell |
Ditto |
Cwd |
Used to set the current directory of the child process |
Env |
The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process. |
Universal_newlines |
Different systems have different line breaks, True-and agree to use \ n |
Startupinfo |
Valid only under Windows, will be passed to the underlying CreateProcess () function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc. |
Createionflags |
Ditto |
import subprocessret1 = subprocess.Popen(["mkdir","t1"])ret2 = subprocess.Popen("mkdir t2", shell=True)
The commands for terminal input are divided into two types:
- Input can be output, such as: ifconfig
- Input to an environment that relies on re-entry, such as: Python
import subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd=‘/home/dev‘,) #在cwd目录下执行命令
import subprocessobj = subprocess. Popen ([ "python"], stdin=subprocess. PIPE, stdout=subprocess. PIPE, stderr=subprocess. PIPE, universal_newlines=true) obj.stdin.write ( "print (1) \ n ") Obj.stdin.write (" print (2) ") obj. stdin.close () cmd_out = Obj.stdout.read () Obj.stdout.close () Cmd_error = Obj.stderr.read () obj. stderr.close () print (cmd_out) print (cmd_error)
import subprocessobj = subprocess. Popen ([ "python"], stdin=subprocess. PIPE, stdout=subprocess. PIPE, stderr=subprocess. PIPE, universal_newlines=true) obj.stdin.write ( "print (1) \ n ") Obj.stdin.write (" print (2) ") Out_error_list = Obj.communicate () print (out_error_list)
import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)out_error_list = obj.communicate(‘print("hello")‘)print(out_error_list)
Python commands module replaced by subprocess in python3.x