Python standard library 06 Sub-process (subprocess package)

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

Thank you.Tolbkni KaoHelp me correct errors

 

The content here is based on the Linux ProcessAnd Linux text stream. The main function of the subprocess package isExecute External commands andProgram. 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.

 

1. subprocess and common encapsulated Functions

When we run python, we are creating and running a process. As described in Linux Process basics, a process canForkA sub-process, and let this sub-processExecAnother 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 them between processes.Text Communication.

 

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.
ReturnExit Information(Returncode is equivalent to exit code. For details, see the Linux Process basics)

 

Subprocess. check_call ()

The parent process waits for the child process to complete.

Return0

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.

ReturnsOutput result

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:

ImportSubprocessrc = 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:

ImportSubprocessout= Subprocess. Call ("Ls-l", Shell =True) Out= Subprocess. Call ("CD ..", Shell = true)

We usedShell = trueThis parameter. At this time, we use1. Entire string, AndNot a tableTo run the sub-process. PythonFirst run a shellAnd use the 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.

 

2. popen

In fact, the above three functions are based onPopen ()Wrapper ). 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 callWait ()Method, the parent process will wait (that is, block blocking ):

ImportSubprocesschild= 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:

ImportSubprocesschild= 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 ()# Killing sub-Processes

Child. send_signal ()# Sending signals to sub-Processes

Child. Terminate ()# Killing sub-Processes

 

The sub-process PID is stored inChild. PID

 

3. Text Flow Control for 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 errors when a sub-process is created in popen ().Subprocess. PipeConcatenates input and output of multiple sub-processes to formMPs queue(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 will block the parent process until the child process is completed.

 

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

 
ImportSubprocesschild= 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 ()

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.