Python's subprocess module summary _python

Source: Internet
Author: User
Tags stdin

Subprocess is intended to replace a few other old modules or functions, such as: Os.system os.spawn* os.popen* popen2.* commands.*
The simplest use of subprocess is to invoke the shell command, or to invoke the program, and to interact with Stdout,stdin and stderr.

Main class of Subprocess

Copy Code code 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)

1), args can be a string or a sequence type (such as: list, tuple), to specify the process executable file and its parameters. If it is a sequence type, the first element is usually the path to the executable file. We can also explicitly use the executeable parameter to specify the path to the executable file.

2), bufsize: Specify the buffer. 0 No buffer, 1 line buffer, other buffer size, negative system buffer (full buffer)

3), stdin, stdout, stderr represent the standard input, output, and error handle of the program respectively. They can be pipe, file descriptors or file objects, or set to none to represent inheritance from the parent process.

4), PREEXEC_FN is only valid under the UNIX platform, and is used to specify an executable object (callable object) that will be invoked before the child process runs.

5), Close_sfs: under the Windows platform, if the Close_fds is set to true, the newly created subprocess will not inherit the parent process's input, output, and error pipes. We cannot set Close_fds to true while redirecting standard input, output, and errors (stdin, stdout, stderr) of the subprocess.

6), the shell is set to True, the program will be executed through the shell.

7), CWD is used to set the current directory of child processes

8), env is the dictionary type that specifies the environment variable for the child process. If env = None, the child process's environment variable inherits from the parent process.
Universal_newlines: Under different operating systems, text line breaks are not the same. For example: Windows uses '/r/n ' to change, while Linux uses '/n '. If this parameter is set to True,python unify these line breaks as '/n ' to be treated. Startupinfo and Createionflags are used only under Windows, and they are passed to the underlying CreateProcess () function to set some of the properties of the child process, such as the appearance of the main window, the priority of the process, and so on.

9), startupinfo and Createionflags are valid only under Windows , and they are passed to the underlying CreateProcess () function to set some of the properties of the child process, such as the appearance of the main window, the priority of the process, and so on.

Popen method

1), Popen.poll (): used to check whether the child process has ended. Sets and returns the ReturnCode property.

2), popen.wait (): wait for child process to end. Sets and returns the ReturnCode property.

3), Popen.communicate (input=none): interacts with child processes. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters to be sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through stdin of the process, the parameter stdin must be set to pipe when the Popen object is created. Similarly, if you want to get data from stdout and stderr, you must set the STDOUT and stderr to pipe.

4), popen.send_signal (signal): send signal to child process.

5), Popen.terminate (): stops (stop) subprocess. Under Windows platform, this method calls the Windows API terminateprocess () to end the subprocess.

6), Popen.kill (): kill the child process.

7), Popen.stdin: If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the subprocess to send instructions. Otherwise, none is returned.

8), Popen.stdout: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the subroutine process to send instructions. Otherwise, none is returned.

9), Popen.stderr: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the subroutine process to send instructions. Otherwise, none is returned.

10), Popen.pid: Gets the process ID of the child process.

11), Popen.returncode: Gets the return value of the process. Returns none if the process is not yet finished.

12), Subprocess.call (*popenargs, **kwargs): Run the command. The function waits until the end of the child process runs and returns the ReturnCode of the process. The first example of the article demonstrates the call function. This function can be used to create a child process if it does not need to interact.

13), Subprocess.check_call (*popenargs, **kwargs): As with Subprocess.call (*popenargs, **kwargs) function, The calledprocesserror exception is triggered only if the ReturnCode returned by the child process is not 0. In the exception object, include the ReturnCode information for the process.

These are all copies.

Run another program or shell in a program

Can write like this

Copy Code code as follows:

Subprocess. Popen (' Script/shell ', shell=true)

I can do that.

Copy Code code as follows:

Subprocess.call (' Script/shell ', shell=true)

The difference is that the former is not blocked, will run in parallel with the main program, the latter must wait for the execution of the command to complete, if you want the former programming blocking can be so
Copy Code code as follows:

s = subprocess. Popen (' Script/shell ', shell=true)
S.wait ()

Program returns run results

Sometimes we need the return result of the program to do so.

Copy Code code as follows:

>>> s = subprocess. Popen (' Ls-l ', Shell=true, stdout=subprocess. PIPE)
>>> S.communicate ()
(' \xe6\x80\xbb\xe7\x94\xa8\xe9\x87\x8f 152\n-rw-------1 Limbo Limbo 808 7\xe6\x9c\x88 6 17:46 0000-00-00-welcome-to-j EKYLL.MARKDOWN.ERB\NDRWX------2 Limbo limbo 4096 8\xe6\x9c\x88 18:43 arg\ndrwx------2 limbo limbo 4096 8\xe6\x9c\ x88 7 17:37 argv\ndrwxrwxr-x 2 limbo limbo 4096 9\xe6\x9c\x88 15:27 c\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9c\x88 One 14:35 d3\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9n ', None

It returns a tuple: (Stdoutdata, Stderrdata)

Subprocess There is another simpler way, the effect is the same, it will return stdout

Copy Code code as follows:

>>> s = subprocess.check_output (' ls-l ', shell=true)
>>> s
' \xe6\x80\xbb\xe7\x94\xa8\xe9\x87\x8f 152\n-rw-------1 Limbo Limbo 808 7\xe6\x9c\x88 6 17:46 0000-00-00-welcome-to-je KYLL.MARKDOWN.ERB\NDRWX------2 Limbo limbo 4096 8\xe6\x9c\x88 18:43 arg\ndrwx------2 limbo limbo 4096 8\xe6\x9c\x 7 17:37 argv\ndrwxrwxr-x 2 limbo limbo 4096 9\xe6\x9c\x88 15:27 c\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9c\x88 One 14:35 d3\ndrwxrwxr-x 3 limbo limbo 4096 '

The former can achieve more interaction, such as stderr and stdin, but implement the definition Popen (stdin=subprocess) before calling Popen. PIPE, Stderr=subprocess)

To enter a child process

Copy Code code as follows:

Import subprocess
Child = subprocess. Popen (["Cat"], stdin=subprocess. PIPE)
Child.communicate ("Vamei")

() is not empty, writes to the subprocess. PIPE, is empty, then from subprocess. Pipe Read


Subprocess. PIPE

Copy Code code as follows:

#!/usr/bin/env python
Import subprocess
Child1 = subprocess. Popen (["LS", "-l"], stdout=subprocess. PIPE)
Child2 = subprocess. Popen (["WC"], stdin=child1.stdout,stdout=subprocess. PIPE)
out = Child2.communicate ()
Print out

It's actually a process like this.

Copy Code code as follows:

Child1.stdout-->subprocess. PIPE

Child2.stdin<--subprocess. PIPE

Child2.stdout-->subprocess. PIPE


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

Subprocess. Pipe actually provides a buffer for the text stream. Until the communicate () method reads the text in the pipe from the pipe. Note that communicate () is a method of the Popen object that blocks the parent process until the child process completes.

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.