"Python" sub-process creation and use subprocess

Source: Internet
Author: User
Tags stdin

Subprocess

This article refers to the http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html of the Vamei great God.

Using the Subprocess package can further open a sub-process under the process of running Python, to create a child process to pay attention to

1. Whether the parent process is paused

2. What is returned by the created child process

3. Execution error, that is, when the returned code is not 0, what should be done

The subprocess package provides three ways to open a subprocess, Subprocess.call (), Subprocess.check_call (), Subprocess.check_output (), and pass the command string as a parameter to the three. This can be in the form of a list ([' Ping ', ' www.baidu.com ', '-C ', ' 3 ']), as well as ("Ping www.baidu.com-c 3"). When you turn on the subprocess, you can add shell=true parameters to allow Python to open a shell and explain the commands you get through the shell. generally run under Windows programs are best to add shell=true, so as to successfully execute the DOS command, but Linux does not seem to add to the matter. Because the Linux does not specify the execution of the shell will call/bin/sh to execute, the problem is not big, but the DOS system will not default with Cmd.exe to execute the command, so add shell=true.

  Subprocess.call; subprocess.check_call; subprocess.check_output the difference between the three is that the returned value is the execution return code of the child process, and returns 0 if the return code is 0. Otherwise the error raise up Calledprocesserror, can use except processing; If the return code is 0 returns the result of the child process to stdout output, otherwise raise. In addition, these three methods are for the parent process to suspend waiting, and the parent process will not continue running until the child process is finished.

In essence, the above three methods are for subprocess. A wrapper for the Popen method, in which the Popen-enabled subprocess does not let the parent process wait for it to complete, unless the wait () method is called:

Child = subprocess. Popen ("...", shell=True)Print "Hello""""It is possible that Hello is printed before the output of the child process because the parent process is not equal to the child process running out""" Child= subprocess. Popen ("...", shell=True) child.wait ()Print "Hello""""This is not the same, the parent process must wait for the child process to finish running, give the complete results before continuing to execute. The equivalent wait function suspends the parent process. """

In addition, the child object in the code above has some other methods:

Child.poll () returns the run state of the child process, mainly two results, none represents not yet running, and a return code indicates that it has completed and is successful or failed

Child.kill () forcibly terminates a child process

Child.send_signal (...) Send a signal to the subprocess (the specific signal is not clear in what way, still pending research )

Child.terminate () terminating child process

PID of Child.pid subprocess

Child.stdin/stdout/stderr standard input stream, standard output, and standard error output, all class file objects

Text Flow control

Each child process object has stdin/stdout/stderr three objects, and three objects can be set when Popen opens a subprocess. Like what

Child1 = subprocess. Popen ("cmd1", Shell=true, stdout=subprocess. PIPE)" "Child1 's stdout is set up as a conduit that can be interpreted as a third-party custodian, since the contents of the Child1 stdout are printed directly to the stdout of the parent process, without setting it. The content is imported into the pipeという third-party escrow facility after it is set up as a pipeline." "child2= subprocess. Popen ("CMD2", shell=true,stdin=child1.stdout,stdout=subprocess. PIPE)" "The stdin of the Child2 was set to Child1 's stdout, which was the third-party organization, so that the data communication between the two sub-processes was realized.
And the Child2 stdout is also set as a third party, because do not want to let child2 output directly to the parent process of the stdout, and to do some processing" "stdout,tmp=child2.communicate ()" "because the output of the child2 is not transferred to a child3 to be processed, the data in the third-party organization is taken out of the communicate method into a variable.
Note that the STDOUT is already a Str object, and the communicate are all strings.
The communicate method comes with the wait feature, which causes the parent process to suspend waiting for all child processes to end
Communicate will return a tuple, but as in this example there is no setting stderr=pipe, so the value of TMP in the tuple of the second item that originally belongs to stderr value is none, if it is set to PIPE, because there is no error message tmp is "". There is a difference in this point. " "Print "We have result:\n%s"% (stdout)#represents the stdout to do some processing before the output

As a matter of fact, I usually do this:

Import= subprocess. Popen ("CMD", shell=true,stdout=subprocess. pipe,stderr== p.communicate ()if"":    print"  ERROR:"+stderrElse:    print"  RESULT:"+stdout

Python Sub-process creation and use of 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.