Python study note 13: Sub-processes of the standard library (subprocess package), pythonsubprocess

Source: Internet
Author: User

Python study note 13: Sub-processes of the standard library (subprocess package), pythonsubprocess
The main function of the ubprocess package is to execute External commands and programs. 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.
In Python, we use the subprocess package in the standard library to fork a sub-process and run an external program.

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.
Returns the exit information (returncode, equivalent to exit code)

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, the error subprocess. CalledProcessError is cited,
This object contains the returncode attribute. try... Else T... To check.

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, the error subprocess. CalledProcessError is cited,
This object contains the returncode and output attributes. The output attribute is the output result of the standard output. try... Else T... To check.

The usage of these three functions is similar to that described in subprocess. call:
Import subprocess
Rc = subprocess. call (["ls", "-l"])
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 subprocessimport subprocesschild = subprocess.Popen(["ping","-c","5","www.google.com"])print("parent process")


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

The shell = True parameter is used. In this case, 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 ):

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 child process
Child. send_signal () # send a signal to the sub-process
Child. terminate () # terminate a child process

The child process PID is stored in child. pid.

Text Flow Control of sub-Processes
Standard input, standard output, and standard errors of sub-processes can also be represented by the following attributes:
Child. stdin
Child. stdout
Child. stderr
We can change the standard input, standard output, and standard errors When Popen () creates a sub-process,
Subprocess. PIPE can be used to connect 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.
Can the subprocess library of python program open a program window?

It is not clear how you want to control a program. What you can do is to input something to the program's standard input, or read the standard output content, or wait for the process to end and read the returned value or even force the process to end. However, if you start a program with a GUI and want to control the GUI, subprocess itself cannot do this. You need to call other windows APIs.
 
Problems with the subprocess module of python

Processing = open (R 'd: \ tmp. log', 'weight ')
Subprocess. Popen (['ipconfig', 'all'], standard output = handle)
..

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.