Python's subprocess module

Source: Internet
Author: User

The relevant modules and functions in Python 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 ') result = Commands.getstatus (' cmd ') result = Commands.getstatusoutput ( ' cmd ')

With the Python version of the update, too many modules caused by the complexity and redundancy of the code, so Python introduced a new module subprocess, the above several modules to focus on the functionality of it, we only need to import this one.

The purpose of subprocess is to start a new process and communicate with it.

1. Call

The parent process waits for the child process to execute the command, returns the status code of the child Process Execution command, and, if an error occurs, does not

"Here's what it means to return the status code of the execution command: if we get the execution result from a variable res = Subprocess.call ([' dir ', shell=true]), we can get a status code that the child process executes the result of the command execution, i.e. RES=0/1 Successful or unsuccessful execution does not mean that you cannot see the results of the execution, and we are able to see the results of the command in the Python console interface, just not getting it. To get the returned results of the execution, see Check_output. 】

"No error Explanation: If we execute the command when the operating system is not recognized, the system will return an error, such as: The ABC command does not exist, the results will be displayed in the console interface, but our Python interpreter will not prompt any information, If you want the Python interpreter to make an error, see Check_call "

#!/usr/bin/env python#-*-coding:utf-8-*-import subprocessprint "################## subprocess.call ###############" The print U "Call method calls the system command to execute, if the error is not an error" Subprocess.call ([' dir '],shell=true)
Note: The shell defaults to False, under Linux, when Shell=false, Popen calls OS.EXECVP () to execute the program specified by args; Shell=true, if Args is a string, Popen directly invokes the system's shell to execute the program specified by args, and if args is a sequence, the first item of args is the definition of the program command string, and the other is additional parameters when invoking the system shell.
Under Windows, Popen calls CreateProcess () to execute the external program specified by args, regardless of the value of the shell. If args is a sequence, it is first converted to a string using List2cmdline (), but it is important to note that not all programs under MS Windows can be converted to command-line strings using List2cmdline. Under Windows, write the shell=true when invoking the script.

return Result:

###### Subprocess.call ###### #call方法调用系统命令进行执行, if the error is not an error D:\Program\Python directory 2016/01/27  11:51             1,069 subprocessdemo.py               1 Files          1,228 bytes

2. Check_call

The parent process waits for the child process to execute the command, returns the status code of the executing command, and, if an error occurs, "If ReturnCode is not 0, give the error subprocess." Calledprocesserror, this object contains the ReturnCode property, which can be try...except ... To check the "

#!/usr/bin/env python#-*-coding:utf-8-*-import subprocessprint "2. The ################## subprocess.check_call ########## "Print U" Check_call is the same as the call command, except that if an error occurs "Subprocess.check_call ( [' dir '],shell=true) subprocess.check_call ([' abc '],shell=true) Print U "Call method with Check_call method both knowledge executes and prints the command to the output terminal, but cannot get to the If you want to get results using Check_output "

return results

2. ################## Subprocess.check_call ######### #check_call与call命令相同, the difference is that if an error occurs, the volume in drive D is not labeled. The serial number of the volume is the directory of C6a1-5ad3 D:\Program\Python 2016/01/27  13:05    <DIR>          . 2016/01/27 13:05    <dir >.          . 2016/01/27  10:44    <DIR>          idea2016/01/27  11:23               159 log_analyse.py2016/01/27  13:05                                 1,329 subprocessdemo.py               2 files          1,488 bytes               3 directories 26,335,281,152 Available Bytes ' abc ' is not an internal or external command, nor is it a program or batch file that can be run. Here is the system error Traceback (most recent call last) returned by the System execution command: Here is the error returned by the Python interpreter  Fil E "d:/program/python/subprocessdemo.py", Line D, in <module>    subprocess.check_call ([' ABC '],shell=true)  File "C:\Python27\lib\subprocess.py", line 540, in Check_call    raise Calledprocesserror (Retcode, cmd) Subprocess. Calledprocesserror:command ' [' abc '] ' returned Non-zero exit status 1

3. Check_output

The parent process waits for the child process to execute the command, returns the child process to send output run results to the standard output, checks for exit information, and, if ReturnCode is not 0, enumerates error subprocess. Calledprocesserror, which contains the ReturnCode property and the output property, outputs a result of the standard output, available try...except ... To check.

#!/usr/bin/env python#-*-coding:utf-8-*-import subprocessprint "3. ################## subprocess.check_output ############## "res1 = Subprocess.call ([' dir '],shell=true) Res2 = Subprocess.check_call ([' dir '],shell=true) Res3 = Subprocess.check_output ([' dir '],shell=true) print U "Call Result:", Res1print u "check_call result:", res2print U "check_output result: \ n", Res3

return Result:

3. ################## Subprocess.output ############## The volume in drive D is not labeled.          The serial number of the volume is the directory of C6a1-5ad3 D:\Program\Python 2016/01/27 13:14 <DIR>. 2016/01/27 13:14 <DIR> ..             2016/01/27 10:44 <DIR> idea2016/01/27 11:23 159 Log_analyse.py2016/01/27 13:14  1,324 subprocessdemo.py 2 files 1,483 bytes 3 directories 26,334,232,576 Available Bytes The volume in drive D is not labeled.          The serial number of the volume is the directory of C6a1-5ad3 D:\Program\Python 2016/01/27 13:14 <DIR>. 2016/01/27 13:14 <DIR> ..             2016/01/27 10:44 <DIR> idea2016/01/27 11:23 159 Log_analyse.py2016/01/27 13:14 1,324 subprocessdemo.py 2 files 1,483 bytes 3 directories 26,334,232,576 free bytes Call Result: 0check_c All results: 0check_output Result: The volume in drive D is not labeled.          The serial number of the volume is the directory of C6a1-5ad3 D:\Program\Python 2016/01/27 13:14 <DIR>. 2016/01/27 13:14 <DIR> .. 2016/01/27 10:44 <dir>. IDEA2016/01/27 11:23 159 log_analyse.py2016/01/27 13:14 1,324 subprocessdemo.py 2 files 1,483 bytes 3 directories 26,334,232,576 Available Bytes

Visible, the Call/check_call return value is the execution status code of the command, and the Check_output return value is the execution result of the command.

If a command is executed with a parameter after it executes, the program name (that is, the command) is placed in a list along with the parameter that is passed to the relevant offence, for example:

>>> import subprocess>>> Retcode = Subprocess.call (["LS", "-l"]) >>> print retcode0

4. Popen

In fact, only one class is defined in the Subprocess module: Popen. Several of the above functions are based on the Popen () package (wrapper). Starting from Python2.4, you can use Popen to create a process that connects to the standard input/output/error of a child process and also gets the return value of the child process. The purpose of these packages is to make it easy for us to use child processes. When we want to personalize our needs more, we turn to the Popen class, which produces objects that represent child processes.

The constructor functions are as follows:

Subprocess. Popen (args, bufsize=0, Executable=none, Stdin=none, Stdout=none, Stderr=none, Preexec_fn=none, Close_fds=false, shell= False, Cwd=none, Env=none, Universal_newlines=false, Startupinfo=none, creationflags=0)

Unlike the package above, the main program does not automatically wait for the child process to complete after the Popen object is created. We have to call the object's Wait () method before the parent process waits (that is, block block).

A) do not wait for the child process

#!/usr/bin/env pythonimport subprocesschild = subprocess. Popen ([' Ping ', '-C ', ' 4 ', ' www.baidu.com ']) print ' Hello '

Execution Result:

Hello [Email protected] script]# PING www.a.shifen.com (61.135.169.125), bytes of data.64 bytes from 61.135.169.125:icmp _seq=1 ttl=55 time=2.04 ms64 bytes from 61.135.169.125:icmp_seq=2 ttl=55 time=1.58 ms64 bytes from 61.135.169.125:icmp_s eq=3 ttl=55 time=2.22 ms64 bytes from 61.135.169.125:icmp_seq=4 ttl=55 time=2.13 ms---www.a.shifen.com ping statistics- --4 packets transmitted, 4 received, 0% packet loss, time 3008msrtt Min/avg/max/mdev = 1.580/1.995/2.220/0.251 ms

As you can see, Python does not wait for the popen operation performed by the child process to complete the print operation.

b) Add child process wait

#!/usr/bin/env pythonimport subprocesschild = subprocess.                             Popen ([' Ping ', '-C ', ' 4 ', ' www.baidu.com '])  #创建一个子进程, process named child, perform Operation Ping-c 4 www.baidu.comchild.wait () #子进程等待print ' Hello '

Execution Result:

[[email protected] script]# python sub.py PING www.a.shifen.com (61.135.169.125) (+) bytes of data.64 bytes from 61.135 .169.125:icmp_seq=1 ttl=55 time=1.82 ms64 bytes from 61.135.169.125:icmp_seq=2 ttl=55 time=1.65 ms64 bytes from 61.135.1 69.125:icmp_seq=3 ttl=55 time=1.99 ms64 bytes from 61.135.169.125:icmp_seq=4 ttl=55 time=2.08 ms---www.a.shifen.com pin G Statistics---4 packets transmitted, 4 received, 0% packet loss, time 3009msrtt Min/avg/max/mdev = 1.656/1.889/2.082/0.1 MsHello

It is seen that Python performs the print operation only after the child process operation is completed.

In addition, you can also perform other operations on the child process in the parent process, such as in our example:

Child.poll () # Check child process Status Child.kill () # terminating child process child.send_signal () # Send signal to Child process child.terminate () # terminating child process
PS: The PID of the child process is stored in child.pid

Child process Text flow control

The standard input, standard output, and standard errors for child processes are represented by the following attributes:

Child.stdin | Child.stdout | Child.stderr

We can also change standard input, standard output, and standard error when Popen () is established, and can take advantage of subprocess. Pipes connect the inputs and outputs of multiple sub-processes together to form a pipe, as in the following 2 examples:


#! /usr/bin/env pythonimport subprocesschild = subprocess. Popen ([' ls ', '-l '],stdout=subprocess. PIPE) #将标准输出定向输出到subprocess. Pipeprint child.stdout.read () #使用 child.communicate () can also be

Output Result:

[email protected] script]# python sub.py total 12-rw-r--r--. 1 root root  07:38 Jan Analyse.sh-rw-r--r--. 1 root root 446 Jan 19:35 sub.py
Example 2#!/usr/bin/env pythonimport subprocesschild1 = subprocess. Popen ([' Cat ', '/etc/passwd '],stdout=subprocess. PIPE) child2 = subprocess. Popen ([' grep ', ' Root '],stdin=child1.stdout,stdout=subprocess. PIPE) Print child2.communicate ()

The output result is

(' root:x:0:0:root:/root:/bin/bash\n, None)

Subprocess. Pipe actually provides a buffer for text flow. The child1 stdout the text out to the buffer, and then Child2 's stdin reads the text from the pipe. The output text of the child2 is also stored in the pipe until the communicate () method reads the text from the pipe.
Note: Communicate () is a method of the Popen object that blocks the parent process until the child process finishes

Child Process Command Interpretation

In the example above, when we created the subprocess, we all called Python to explain it, but Python did not interpret all the commands, and when Python was unable to interpret it, it was ready to invoke the system for execution.

#!/usr/bin/env Pythonimport subprocesssubprocess. Popen ([' ls ', '-l ']) subprocess. Popen ([' Ifconfig|grep 127.0.0.1 '],shell=true)

Results

>>> subprocess. Popen ([' Ifconfig|grep 127.0.0.1 '],shell=true) <subprocess. Popen object at 0x7f25eb0c1350>>>>           inet addr:127.0.0.1  mask:255.0.0.0

Python's subprocess module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.