[Python programming] subprocess Module Learning Summary

Source: Internet
Author: User

Reprint: http://www.jb51.net/article/48086.htm

Starting with Python 2.4, Python introduced the Subprocess module to manage sub-processes to replace some of the old modules: Os.system, os.spawn*, os.popen*, popen2.*, commands.* Not only can the external command be called as a child process, but it can also be connected to the Input/output/error pipeline of the child process to get the related return information.

One, subprocess, and common encapsulation functions
    When you run Python, we are creating and running a process. Like the Linux process, a process can fork a child process and let the child process exec another program. In Python, we fork a child process through the subprocess package in the standard library and run an external program. The
Subprocess package defines a number of functions that create child processes, each of which creates child processes in different ways, so we can pick a use from them as needed. In addition, Subprocess provides some tools for managing standard streams and pipelines (pipe) to use text communication between processes.
Subprocess.call ()
Parent process waits for child process to finish
return exit information (ReturnCode, equivalent to Linux exit code)
Subprocess.check_call ()
The parent process waits for the child process to complete
return 0
to check the exit information, and if ReturnCode is not 0, the error subprocess is enumerated. Calledprocesserror, this object contains the ReturnCode property, which can be try...except ... To check the
subprocess.check_output ()
Parent process waits for the child process to finish
return the output from the child process to the standard output
Check the exit information, if ReturnCode is not 0, The error subprocess is cited. Calledprocesserror, which contains the ReturnCode property and the output property, outputs a result of the standard output, available try...except ... To check.
These three functions are used in a similar way, as illustrated below with Subprocess.call ():

Import= Subprocess.call (["ls""-L"# and the command ls-l in the shell shows the same result. Print Retcode

Place the program name (LS) with the parameter (-L) in a table and pass it to Subprocess.call ()
The shell defaults to False, under Linux, when Shell=false, Popen calls OS.EXECVP () to execute the program specified by args, or shell=true, if args is a string, Popen directly invokes the system's shell to execute the program specified by args, and if args is a sequence, the first item of args is the definition of the program command string, and the other is additional parameters when invoking the system shell.
The above example can also be written as follows:

Retcode = Subprocess.call ("ls-l", Shell=true)

Under Windows, Popen calls CreateProcess () to execute the external program specified by args, regardless of the value of the shell. If args is a sequence, it is first converted to a string using List2cmdline (), but it is important to note that not all programs under MS Windows can be converted to command-line strings using List2cmdline.

Subprocess. Popen ()

class Popen (args, bufsize=0, Executable=none, Stdin=none, Stdout=none, Stderr=none, Preexec_fn=none, Close_fds=false, shell= False, Cwd=none, Env=none, Universal_newlines=false, Startupinfo=none, creationflags=0)

In fact, several of the above functions are based on the Popen () package (wrapper). The purpose of these packages is to make it easy for us to use child processes. When we want to personalize our needs more, we turn to the Popen class, which produces objects that represent child processes.
Unlike the package above, the main program does not automatically wait for the child process to complete after the Popen object is created. We must call the object's Wait () method, and the parent process waits (that is, block blocks), for example:

Import= subprocess. Popen (['ping','-C','4', ' 192.168.0.1 ' ])print'parent process'

As seen from the results of the run, the parent process does not wait for the child to complete after it has been opened, but runs print directly.
Comparison of waiting conditions:

Import= subprocess. Popen ('ping-c4 blog.linuxeye.com', shell=True) child.wait ()print  'parent process'

As you can see from the results of the run, the parent process runs print after the child process is opened and waits for the children to complete.
In addition, you can also perform other operations on the child process in the parent process, such as in our example:

# Check child process status # terminating a child process # send a signal to a child process # terminating a child process

The PID of the child process is stored in the Child.pid

Text flow control of sub-process
The standard input, standard output, and standard errors for child processes are represented by the following attributes:

Child.stdinchild.stdoutchild.stderr

You can change standard input, standard output, and standard errors when Popen () is established, and can take advantage of subprocess. Pipes connect the inputs and outputs of multiple sub-processes together to form a pipe, as in the following 2 examples:

ImportSubprocesschild1= subprocess. Popen (["ls","- L"], stdout=subprocess. PIPE)PrintChild1.stdout.read ()#or child1.communicate ()ImportSubprocesschild1= subprocess. Popen (["Cat","/etc/passwd"], stdout=subprocess. PIPE) Child2= subprocess. Popen (["grep","0:0"],stdin=child1.stdout, stdout=subprocess. PIPE) out= Child2.communicate ()

Subprocess. Pipe actually provides a buffer for text flow. The child1 stdout the text out to the buffer, and then Child2 's 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 from the pipe.
Note: Communicate () is a method of the Popen object that blocks the parent process until the child process finishes

[Python programming] subprocess Module Learning Summary

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.