Python module learning-subprocess creating sub-Processes

Source: Internet
Author: User
Document directory
  • Subprocess. 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)
  • Subprocess. Pipe
  • Subprocess. stdout

Recently, our boss asked me to write a Guardian program to guard server processes. If the server crashes, the guardian can immediately restart the application. I googled the Internet and found that many Python modules can be used to create processes. In the end, I chose to use the subprocess module because the python manual contains the following:

This module intends to replace several other, older modules and functions, such as: OS. System, OS. Spawn *, OS. popen *, popen2. *, commands .*

Subprocess is used to replace some old modules and functions, such as OS. System, OS. Spawn *, OS. popen *, popen2. *, and commands .*. It can be seen that subprocess is a recommended module.

 

The following is a simple example: Create a new process, execute app1.exe, pass in equivalent parameters, and print the return value of the process:

Import subprocess </P> <p> returncode = subprocess.call('app1.exe-a-B-c-d') <br/> Print 'returncode :', returncode </P> <p> # ----- result -------- <br/> # python is powerful <br/> #app1.exe <br/> #-A <br/> #-B <br/> #-C <br/> #-D <br/> returncode: 0

App1.exe is a very simple console program that prints only the input parameters. The Code is as follows:

 # Include <iostream> <br/> using namespace STD; </P> <p> int main (INT argc, const char * argv []) <br/> {<br/> cout <"python is powerful" <Endl; <br/> for (INT I = 0; I <argc; I ++) <br/>{< br/> cout <argv [I] <Endl; <br/>}</P> <p> return 0; <br/>}

Let's talk less about it. Next we will introduce the subprocess module in detail. The Subprocess module defines only one class: popen. You can use popen to create a process and perform complex interaction with the process. Its constructor is as follows:

Subprocess. 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)

The args parameter can be a string or a sequence type (such as list and tuples). It is used to specify the executable file of a process and its parameters. For the sequence type, the first element is usually the path of the executable file. You can also explicitly use the executeable parameter to specify the path of the executable file. In Windows, popen creates a sub-process by calling CreateProcess (). CreateProcess receives a string parameter. If ARGs is of the sequence type, the system uses list2cmdline () the function converts the sequence type to a string.
Bufsize: Specify the buffer. I still don't know the specific meaning of this parameter. I hope you can give me some advice.
Executable is used to specify the executable program. Generally, the ARGs parameter is used to set the program to run. If the shell parameter is set to true, executable specifies the shell used by the program. On Windows, the default shell is specified by the comspec environment variable.
The stdin, stdout, and stderr parameters respectively indicate the standard input, output, and error handle of the program. They can be pipe, file descriptor or file object, or set to none, indicating that they are inherited from the parent process.
The preexec_fn parameter is valid only on the UNIX platform and is used to specify a callable object, which will be called before the sub-process runs.
Close_sfs: On Windows, if close_fds is set to true, the newly created sub-process will not inherit the input, output, and error pipelines of the parent process. We cannot set close_fds to true and redirect the standard input, output, and error (stdin, stdout, stderr) of the sub-process ).
If the shell parameter is set to true, the program will execute it through shell.
The CWD parameter is used to set the current directory of the sub-process.
The env parameter is a dictionary type used to indicate the environment variables of the child process. If Env = none, the environment variables of the child process are inherited from the parent process.
Universal_newlines: The text line breaks vary with operating systems. For example, in windows, '/R/N' is used, while in Linux,'/N' is used '. If this parameter is set to true, Python treats these linefeeds as '/N.
The startupinfo and createionflags parameters are valid only in windows. They are passed to the underlying CreateProcess () function to set attributes of sub-processes, such as the appearance of the main window, process Priority.

Subprocess. Pipe

When creating a popen object, subprocess. pipe can initialize the stdin, stdout, or stderr parameters. Indicates the standard stream that communicates with the sub-process.

Subprocess. stdout

When a popen object is created, it is used to initialize the stderr parameter, indicating that the error is output through the standard output stream.

 

Popen method:

Popen. Poll ()

Used to check whether the sub-process has ended. Set and return the returncode attribute.

Popen. Wait ()

Wait until the child process ends. Set and return the returncode attribute.

Popen. Communicate (input = none)

Interacts with sub-processes. Send data to stdin or read data from stdout and stderr. Optional parameter input specifies the parameter sent to the sub-process. Communicate () returns a tuples (stdoutdata, stderrdata ). Note: If you want to send data to the process through stdin, The stdin parameter must be set to pipe when you create a popen object. Similarly, if you want to obtain data from stdout and stderr, you must set stdout and stderr to pipe.

Popen. send_signal (signal)

Sends signals to sub-processes.

Popen. Terminate ()

Stop the sub-process. On Windows, this method calls the Windows API terminateprocess () to end the child process.

Popen. Kill ()

Kill the child process.

Popen. stdin

If the popen object is created, the stdin parameter is set to pipe, and popen. stdin returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. stdout

If the popen object is created, the stdout parameter is set to pipe, and popen. stdout returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. stderr

If the popen object is created, the stdout parameter is set to pipe, and popen. stdout returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. PID

Obtain the ID of the sub-process.

Popen. returncode

Obtain the return value of a process. If the process has not ended, none is returned.

The following is a very simple example to demonstrate how the supprocess module interacts with a console application.

 Import subprocess </P> <p> P = subprocess. popen ("app2.exe", stdin = subprocess. pipe,/<br/> stdout = subprocess. pipe, stderr = subprocess. pipe, shell = false) </P> <p> P. stdin. write ('3/N') <br/> P. stdin. write ('4/N') <br/> Print p. stdout. read () </P> <p> # ---- result ---- <br/> input x: <br/> input Y: <br/> 3 + 4 = 7

App2.exe is also a very simple console program. It receives two values from the interface, performs the add operation, and prints the results to the console. The Code is as follows:

 # Include <iostream> <br/> using namespace STD; </P> <p> int main (INT argc, const char * artv []) <br/>{< br/> int X, Y; <br/> cout <"input x:" <Endl; <br/> CIN> X; <br/> cout <"input Y:" <Endl; <br/> CIN> Y; <br/> cout <x <"+" <Y <"=" <X + Y <Endl; </P> <p> return 0; <br/>}

 

The supprocess module provides some functions for you to create a process.

Subprocess. Call (* popenargs, ** kwargs)

Run the command. This function waits until the sub-process finishes running and returns the returncode of the process. The example at the beginning demonstrates the call function. If the sub-process does not need to interact with each other, you can use this function to create a sub-process.

Subprocess. check_call (* popenargs, ** kwargs)

Similar to the subprocess. Call (* popenargs, ** kwargs) function, a calledprocesserror exception is triggered if the returncode returned by the child process is not 0. The exception object contains the returncode information of the process.

 

There is so much content in the subprocess module. The Python Manual also describes how to use subprocess to replace some old modules and functions. If you are interested, you can take a look.

 

Reference:

Subprocess-subprocess Management

Pymotw: subprocess

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.