Python standard library subprocess package details

Source: Internet
Author: User
The content here is based on the Linux process and Linux text stream. 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 call the wget program in Python. In this sense, subprocess functions are similar to shell. Subprocess and common encapsulation functions when we run python, we create and run the content here based on the Linux process and Linux text stream. 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 call the wget program in Python. In this sense, subprocess functions are similar to shell.

Subprocess and common encapsulated functions

When we run python, we are creating and running a process. As we introduced in Linux process basics, a process can fork a sub-process and let the sub-process exec another program. In Python, we use the subprocess package in the standard library to fork a sub-process and run an external program (fork and exec refer to the Linux process basics ).

The subprocess package defines several functions for creating sub-processes. these functions are used to create sub-processes in different ways. Therefore, you can select a sub-process as needed. In addition, subprocess provides some tools for managing standard streams and pipelines to use text communication between processes.

When using the functions in the subprocess package to create sub-processes, note the following:

1) after a child process is created, check whether the parent process is paused and wait for the child process to run.

2) What does the function return?

3) how to handle a parent process when the returncode is not 0.

subprocess.call()



The parent process waits for the child process to complete.

Return the exit information (returncode, equivalent to exit code, see The Linux process basics)

subprocess.check_call()


The parent process waits for the child process to complete.

Returns 0.

Check the exit information. if the returncode is not 0, an error subprocess is thrown. calledProcessError, which contains the returncode attribute. try... else t... to check (see Python error handling ).

subprocess.check_output()



The parent process waits for the child process to complete.

Returns the output result of the sub-process to the standard output.

Check the exit information. if the returncode is not 0, an error subprocess is thrown. calledProcessError. this object contains the returncode attribute and output attribute. the output attribute is the output result of the standard output. try... else t... to check.

The usage of these three functions is similar. We use subprocess. call () to describe:

import subprocessrc = subprocess.call(["ls","-l"])



We put the program name (ls) and the parameter (-l) together in a table and pass it to subprocess. call ()

You can use a shell to explain the entire string:

import subprocessout = subprocess.call("ls -l", shell=True)out = subprocess.call("cd ..", shell=True)



We use the shell = True parameter. At this time, we use an entire string instead of a table to run the sub-process. Python will first run a shell, and then use this shell to explain the entire string.

Shell commands include some built-in shell commands, which must be run through shell, $ cd. Shell = True allows us to run such commands.

Popen ()

In fact, the above three functions are all wrapper based on Popen ). These encapsulation aims to make it easy to use sub-processes. When we want to personalize our needs, we need to turn to the Popen class, which generates objects to represent sub-processes.

Unlike the preceding encapsulation, after a Popen object is created, the main program does not automatically wait for the child process to complete. We must call the wait () method of the object before the parent process will wait (that is, block blocking ):

import subprocesschild = subprocess.Popen(["ping","-c","5","www.google.com"])print("parent process")



The running result shows that the parent process does not wait for the completion of child after starting the child process, but runs print directly.

Compare the waiting conditions:

import subprocesschild = subprocess.Popen(["ping","-c","5","www.google.com"])child.wait()print("parent process")



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

Child. poll () # Check the sub-process status child. kill () # Stop the sub-process child. send_signal () # send the signal child. terminate () to the sub-process # Stop the sub-process


The child process PID is stored in child. pid.

Text flow control of sub-processes

Standard input of child processes. standard output and standard errors can also be indicated by the following attributes:

Child. stdin

Child. stdout

Child. stderr

We can change the standard input, standard output, and standard error when creating a sub-process in Popen (), and use subprocess. PIPE connects the input and output of multiple sub-processes to form a pipeline (pipe ):

import subprocesschild1 = 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 cache for text streams. The stdout of child1 outputs the text to the cache, and then the stdin of child2 reads the text from the PIPE. The output text of child2 is also stored in PIPE until The communicate () method reads the text in PIPE from PIPE.

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

We can also use the communicate () method to use PIPE to input the sub-process:

import subprocesschild = subprocess.Popen(["cat"], stdin=subprocess.PIPE)child.communicate("vamei")


After we start the process, cat will wait for the input until we enter "vamei" with communicate ".

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

Summary

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

Subprocess. Popen (), subprocess. PIPE

Popen. wait (), Popen. communicate ()


The above is a detailed description of the subprocess package of the Python standard library sub-process. For more information, see other related articles in the first PHP community!

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.