Python Standard library 06 sub-process (subprocess package) detailed _python

Source: Internet
Author: User
Tags error handling stdin in python

The content here is based on Linux process basics and Linux text streaming. The main function of the subprocess package is to execute external commands and programs. For example, I need to use wget to download files. I invoke the wget program in Python. In this sense, the subprocess function is similar to the shell.

Subprocess and commonly used encapsulation functions

When we run Python, we are creating and running a process. As we described in the Linux process basics, a process can fork a subprocess and let this child process exec another program. In Python, we fork a subprocess through the subprocess package in the standard library and run an external program (Fork,exec see the Linux process Basics).

The subprocess package defines a number of functions that create child processes, which create child processes in different ways, so we can select one to use as needed. In addition, Subprocess provides tools for managing standard streams (standard stream) and pipelines (pipe) to use text communication between processes.

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

1 after the child process is created, the parent process is paused and waits for the child process to run.

2 What does the function return?

3 when the ReturnCode is not 0 o'clock, how the parent process is handled.

Subprocess.call ()

The parent process waits for the child process to complete

Return exit information (ReturnCode, equivalent to exit code, see Linux process Basics)

Subprocess.check_call ()

The parent process waits for the child process to complete

return 0

Check the exit information, and if the ReturnCode is not 0, cite the error subprocess. Calledprocesserror, this object contains ReturnCode properties, available try...except ... To check (see Python error handling).

Subprocess.check_output ()

The parent process waits for the child process to complete

Returns the output of the child process to the standard output

Check the exit information, and if the ReturnCode is not 0, cite the error subprocess. Calledprocesserror, the object contains ReturnCode and output properties, output properties for standard output, available try...except ... To check.

These three functions are used in a similar way, and we use Subprocess.call () to illustrate:

Import subprocess
rc = Subprocess.call (["LS", "-l"])

We pass the program name (LS) with the parameter (-L) in a table to Subprocess.call ()

You can use a shell to interpret an entire string:

Import subprocess Out
= Subprocess.call ("Ls-l", shell=true) out
= Subprocess.call ("CD ...", Shell=true)

We used the Shell=true parameter. At this time, we use an entire string instead of a table to run the child process. Python will run a shell first, then use this shell to interpret the entire string.

Some of the shell commands are shell-built commands that must be run through the shell, $CD. Shell=true allows us to run some of these commands.

Popen ()

In fact, all three of our above functions are based on popen () encapsulation (wrapper). The purpose of these packages is to make it easy for us to use the child processes. When we want to personalize our needs, we turn to the Popen class, which generates objects to represent the subprocess.

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

Import subprocess Child
= subprocess. Popen (["Ping", "-C", "5", "www.google.com"])
print ("Parent process")

As you can see from the run results, the parent process does not wait for the child to complete but instead runs print directly after the subprocess is opened.

Compare the waiting situation:

Import subprocess Child
= subprocess. Popen (["Ping", "-C", "5", "www.google.com"])
child.wait ()
print ("Parent process")

In addition, you can do other things in the parent process, such as the child object in our example above:

Child.poll ()      # Check child process status

Child.kill ()      # terminating subprocess

child.send_signal ()  # Sending signals

to child processes Child.terminate ()   # terminating child processes

PID for child processes is stored in child.pid

Text flow control for child processes

Standard input of child processes (following the child subprocess) can also be represented by standards output and standard errors as follows:

    • Child.stdin
    • Child.stdout
    • Child.stderr

We can change standard input, standard output, and standard error when popen () build a subprocess, and can use subprocess. Pipe joins the inputs and outputs of multiple child processes together to form a pipe (pipe):

Import subprocess
child1 = subprocess. Popen (["LS", "-l"], stdout=subprocess. PIPE)
child2 = subprocess. Popen (["WC"], stdin=child1.stdout,stdout=subprocess. PIPE) Out
= Child2.communicate ()
print (out)

Subprocess. Pipe actually provides a buffer for the text stream. Child1 's stdout outputs the text to the buffer, and then child2 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 in pipe from the pipe.

Note that communicate () is a method of the Popen object that blocks the parent process until the child process completes.

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

Import subprocess Child
= subprocess. Popen (["Cat"], stdin=subprocess. PIPE)
child.communicate ("Vamei")

After we start the subprocess, cat waits for input until we enter "Vamei" with communicate ().

By using the subprocess package, we can run external programs. This greatly expands the functionality of Python. If you already know some of the applications of the operating system, you can invoke the application directly from Python (rather than relying entirely on Python) and output the results of the application to Python and let Python continue with it. Shell functions, such as using text streams to connect various applications, can be implemented in Python.

Summarize

Subprocess.call, Subprocess.check_call (), Subprocess.check_output ()

Subprocess. Popen (), subprocess. PIPE

Popen.wait (), Popen.communicate ()

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.