Python Module Accumulation-----subprocess

Source: Internet
Author: User
Tags assert posix stdin

    • Subprocess Module Introduction

Subprocess is a tool for Python to create child processes, and in fact a fork in C is a child process, and then running exec in a child process executes another process very similar.

There are many ways to create child processes in the subprocess package, and these functions create sub-processes that behave differently, and we can choose different ways to create child processes.

When creating child processes using the functions in the subprocess package, be aware that:

1) Whether the parent process pauses after the child process is created and waits for the child process to run.

2) What the function returns

3) How the parent process handles when ReturnCode is not 0 o'clock.

    • Subprecess.call ()

Subprocess.call ()
Parent process waits for child process to complete
Return exit information (ReturnCode, equivalent to exit code)

Subprocess.check_call ()

Parent process waits for child process to complete

Returns 0

Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, this object contains the ReturnCode property, which can be try...except ... To check).

Subprocess.check_output ()

Parent process waits for child process to complete

Returns the output of the child process to the standard output

Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, which contains the ReturnCode property and the output property, outputs a result of the standard output, available try...except ... To check.

  

1 #include <iostream> 2 #include <unistd.h> 3  4 using namespace std; 5  6 int main (int argc, const char *argv[]) 7 {8     cout << "Python is powerful" << Endl, 9 for     (int i = 0; i < argc; i++)     {         cout << argv[i] << Endl;     Sleep (ten);     return 0;  16}  ~           
1 #!/usr/bin/env python 2  3 import subprocess 4  5 ReturnCode = Subprocess.call (' ls-l ', shell=true)  
We used the Shell=true parameter. At this point, we use an entire string instead of a table to run the child process. Python will run a shell first and then use this shell to interpret the entire string.
6 print "ReturnCode:", ReturnCode 7 8 ReturnCode = subprocess.call ([' ls ', '-l '])
We put the program name (LS) together with the parameter (-L) in a table passed to Subprocess.call ()

The app also passes the parameters and the app itself as a list of past
Print "ReturnCode:", ReturnCode

Execution Result:

[Email protected]:~/desktop/go$./assert.py Total 1256-rwxr-xr-x 1 yca yca 7785 2013-05-07    20:02 app-rw-r--r--1 Yca y CA     221 2013-05-07 20:01 app.cpp-rwxr-xr-x 1 yca yca 217     2013-05-07 20:40 assert.py-rwxr-xr-x 1 yca yca 1256270 201 3-04-28 02:30 hello-rw-r--r--1 yca yca 396     2013-05-01 19:59 hello.go-rw-r--r--1 yca yca     918 2013-05-07 01:08 Hel loworld.go-rw-r--r--1 Yca yca     556 2013-05-07 02:43 Map.goreturncode:0python is powerful./app-a-b-c-dreturncode:0

    • Subprocess. Popen ()

All three of the above functions are for subprocess. Popen encapsulation, 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.

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

  

1 #!/usr/bin/env python2 3 Import subprocess4 5 ReturnCode = subprocess. Popen (['./app ', '-a ', '-B ', '-c ', '-d ']) 6 print "Parent process"

[Email protected]:~/desktop/go$./assert.py parent Process[email protected]:~/desktop/go$ Python is powerful./ App-a-b-c-d

As seen from the results of the run, the parent process does not wait for the child to complete after it has been opened, but runs print directly.

1 #!/usr/bin/env python2 3 import subprocess4 5 child = subprocess. Popen (['./app ', '-a ', '-B ', '-c ', '-d ']) 6 ReturnCode = child.wait () 7 print "ReturnCode:", ReturnCode
8 print "Parent process"
[Email protected]:~/desktop/go$./assert.py Python is powerful./app-a-b-c-d
Returncode:0parent process

It's obvious that the parent process is waiting for the child process to finish before it starts executing

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 a signal to a child process

Child.terminate () # terminating child process

1.popen.poll (): Used to check whether the child process has ended. Sets and returns the ReturnCode property. 2.popen.wait (): Waits for the child process to end. Sets and returns the ReturnCode property. 3.popen.communicate (Input=none): interacts with child processes. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters that are sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through the process's stdin, the parameter stdin must be set to pipe when the Popen object is created. Similarly, if you want to get data from stdout and stderr, you must set stdout and stderr to pipe. 4.popen.send_signal (signal): Sends a signal to the child process. 5.popen.terminate (): Stop (stop) child process. Under the Windows platform, this method will call Windows API TerminateProcess () to end the child process. 6.popen.kill (): Kills the child process. 7.popen.stdin: If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the policy child process send instruction. Otherwise, none is returned. 8.popen.stdout: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned. 9.popen.stderr: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned. 10.popen.pid: Gets the process ID of the child process. 11.popen.returncode: Gets the return value of the process. Returns none if the process is not finished yet. 12.subprocess.call (*popenargs, **kwargs): Runs the command. The function waits until the child process finishes running and returns the ReturnCode of the process. The first example of this article demonstrates the call function. You can use this function to create a child process if it does not need to interact. 13.subprocess.check_call (*popenargs, **kwargs): With Subprocess.call (*popenargs, **kwargs), except that the calledprocesserror exception is triggered if the child process returns a returncode that is not 0. In the exception object, include the ReturnCode information for the process.

The PID of the child process is stored in the Child.pid

The Popen object Popen object has the following methods: Popen.poll () checks whether the child process has ended, sets and returns the ReturnCode property. Popen.wait () Waits for the child process to end, sets and returns the ReturnCode property. Note: If a child process outputs a large amount of data to a stdout or stderr pipeline and reaches the system pipe's cache size, the child process waits for the parent process to read the pipeline, and the parent process is waiting for the legendary deadlock, and the consequences are very serious. It is recommended to use communicate () to avoid this situation. Popen.communicate (Input=none) interacts with child processes: sends data to STDIN, and reads data from stdout and stderr until EOF is received. Wait for the child process to end. The optional input, if any, is the string type. This function returns a tuple: (Stdoutdata, Stderrdata). Note that to send data to the stdin of the child process, the Popen, stdin to be pipe, similarly, to be able to receive data, stdout or stderr also for pipe. Note: The data read will be cached in memory, so be careful when the amount of data is very large. Popen.send_signal (signal) sends signal semaphore to the child process. Note: Only send Sigterm is currently supported under Windows, equivalent to the following terminate (). Popen.terminate () stops the child process. POSIX is the sending of sigterm signals. Windows is called TerminateProcess () this API. Popen.kill () kills the child process. POSIX is the sending of sigkill signals. Windows and terminate () are the same. Popen.stdin if the stdin parameter is a pipe, this property is a file object, otherwise none. Popen.stdout If the stdout parameter is a pipe, this property is a file object, otherwise none. Popen.stderr if the stderr parameter is a pipe, this property is a file object, otherwise none. The process number of the Popen.pid child process. Note that if the shell parameter is true, this property refers to the child shell's process number. The return value of the Popen.returncode subroutine, set by poll () or wait (), is also indirectly set by communicate (). If none, indicates that the child process has not been terminated. If negative-n indicates that the child process is nsignal termination. (*nux only)

http://blog.csdn.net/mr_jj_lian/article/details/6936984

3. Text flow control for child processes

Standard input, standard output, and standard errors can also be represented by the following properties (in the child process):

Child.stdin

Child.stdout

Child.stderr

We can 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 pipeline (pipe):

Child1.stdout-->subprocess. PIPE

Child2.stdin<--subprocess. PIPE

Child2.stdout-->subprocess. PIPE

Equivalent to the child1.stdout-->child2.stdin->child2.stdout->subprocess. PIPE

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 that communicate () is a method of the Popen object that blocks the parent process until the child process finishes.

We can also use the communicate () method to input a child process using a pipe:

1 Import subprocess2 child = subprocess. Popen (["Cat"], stdin=subprocess. PIPE) 3 child.communicate ("Vamei")//() is not empty, then write to subprocess. PIPE, empty, then from subprocess. Pipe Read
Subprocess. Pipe-->child.stdin

Commiuncate is equivalent to writing subprocess. PIPE, and then child from subprocess. Pipe Read

    • ReturnCode

Where does the return value after the child process is executed? The return value of exit is obtained by

  

1 #!/bin/bash2 3 echo "Hello" 4 exit 15 ~             
1 #!/usr/bin/env python2 3 import subprocess4 5 child = subprocess. Popen (["./shell.sh"], stdout=subprocess. PIPE) 6 ReturnCode = child.wait () 7 print "ReturnCode:", returnCode8 stdout = child.communicate () 9 Print stdout

[Email protected]:~/desktop/go$./assert.py returncode:1 (' hello\n ', None)

Python Module Accumulation-----subprocess

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.