Subprocess Module
允许你生成一个或多个进程,并且可以跟它交互,并且获取返回的结果,这个模块想要替换掉几个老的方法: os.system os.spawn* 所以以后跟系统交互的命令,尽量用subprocess建议调用subprocess的run()方法去跟系统进行调用,更高级的方法,使用popen() ;run()方法其实就是封装的popen。run()方法在python3.5才有,python2.x没有,2.x用subprocess.call(),当然python3.X版本也支持call()
Common methods of subprocess
subprocess.call subprocess.call ("Df-lh", shell=true) or Subprocess.call (["DF", "-LH"]) if you want to get to the execution content: A = subprocess. Popen ("Df-lh", shell=true,stdout=subprocess. PIPE) A.stdout.read () Subprocess.check_call executes the command, if the execution status code is 0, then returns 0, otherwise throws an exception subprocess.check_call (["LS", "-l"]) Subprocess.check_call ("Exit 1", Shell=true) throws an exception: Subprocess. CalledProcessError:subprocess.check_output executes the command, if the status code is 0, returns the execution result, otherwise throws an exception subprocess.check_output (["Echo", "Hello Worl d! "]) return: ' Hello world!\n ' Subprocess.check_output ("Exit 1", Shell=true) Split exception: Subprocess. Calledprocesserror executes the command and returns the result, note that the result is returned, not printed, and the following example returns to res res = Subprocess.getoutput ("ls/bin/sh") Res output: '/BIN/S H ' subprocess.getstatusoutput receives a string format command, returns the tuple form, the 1th element is the execution state, and the 2nd is the command result subprocess.getstatusoutput ("Ls/bin/ls") returns : (0, '/bin/ls ') subprocess.getoutput receives the string format command and returns the result Subprocess.getoutput ("Ls/bin/ls") returned: '/bin/ls '
The Subprocess method above, the bottom is encapsulated Subprocesspopen
Other explanations for subprocess:
poll() Check if child process has terminated. Returns returncodewait() Wait for child process to terminate. Returns returncode attribute.terminate() 杀掉所启动进程communicate() 等待任务结束stdin 标准输入stdout 标准输出stderr 标准错误pid The process ID of the child process.Popen例子: p = subprocess.Popen("df -lh|grep root",stdin=subproce p.stdout.read() 输出:b‘/dev/mapper/cl-root 38G 5.7G 32G 16% /\n‘
Use of the Run () method:
subprocess.run(["ls","-lh"]) subprocess.run("exit 1",shell=True,check=True) 抛出异常:subprocess.CalledProcessError subprocess.run(["ls","-l","/dev/null"],stdout=subprocess.PIPE) 输出: 如下:CompletedProcess(args=[‘ls‘, ‘-l‘, ‘/dev/null‘], returncode=0, stdout=b‘crw-rw-rw-. 1 root root 1, 3 Jan 3 11:16 /dev/null\n‘)调用和系统之间的操作,推荐subprocess.run() ,因为它迟早要替换掉sys.system ;run()方法可以满足大部分的需求,如果要进行一些复杂的交互的话,还可以用subprocessPopen()如: p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE) print (p.stdout.read()) 输出:b‘0 -r--------. 1 root root 128T Jan 23 14:58 /proc/kcore\n1.9G -rw-------. 1 root root 100G Jan 8 17:48 /var/lib/docker/devicemapper/devicemapper/data\n3.8M -rw-------. 1 root root 2.0G Jan 8 17:48 /var/lib/docker/devicemapper/devicemapper/metadata\n‘
Subprocess. Popen (...)
Used to execute complex system command parameters: The Args:shell command, which can be a string or sequence type (for example: list, tuple) BufSize: Specifies Buffering. 0 unbuffered, 1 rows buffered, other buffer sizes, negative system buffers stdin, stdout, stderr: Represents the standard input, output, and error handles of the program, respectively PREEXEC_FN: valid only on UNIX platforms for specifying an executable object (callable O Bject), which will be called CLOSE_SFS before the child process runs: Under Windows platform, if Close_fds is set to true, the newly created child process will not inherit the parent process's input, output, and error pipes. Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process. Shell: Ibid. CWD: Used to set the current directory for a child process env: The environment variable that specifies the child process. If env = None, the environment variables of the child process are inherited from the parent process. Universal_newlines: Different system newline characters, True----agree to use \ n startupinfo and createionflags only valid under Windows will be passed to the underlying CreateProcess () function, with To set some properties of the child process, such as: the appearance of the main window, the priority of the process, and so on the terminal input commands are divided into two: input can be output: such as Ifocnfig input for an environment, dependent on an environment re-input: example of Python need to interact with the command sample: Import Subproce SS obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE) Obj.stdin.write (' Print 1 \ n ') obj.stdin.write (' Print 2 \ n ') obj.stdin.write (' Print 3 \ n ') #当从这里开始就报错了. Obj.stdin.write (' Print 4 \ n ') out_error_list = Obj.communicate ("timeout=Print out_error_list output: (', ' File ' <stdin> ', line 2\n print 2 \ n ^\nindentationerror:un Expected indent\n ') subprocess implement iptables clear rules sudo automatically enter password import subprocess def mypass (): Mypass = ' 123 ' # Or get the password from anywhere return mypass echo = subprocess. Popen ([' Echo ', Mypass ()], stdout=subprocess. PIPE,) sudo = subprocess. Popen ([' sudo ', '-s ', ' iptables ', '-l '], stdin=echo.stdout, STDOUT=SU Bprocess. PIPE,) End_of_pipe = sudo.stdout print ("Password OK \ Iptables Chains%s"% End_of_pip E.read ())
Python subprocess module