Python's subprocess Module summary

Source: Internet
Author: User
Subprocess is intended to replace several other older modules or functions, such as: Os.system os.spawn* os.popen* popen2.* commands.*
The simplest use of subprocess is to invoke the shell command, and also to invoke the program, and to interact with Stdout,stdin and stderr.

Main class of Subprocess

The code 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)

1), args can be a string or sequence type (for example: list, tuple) that specifies the process's 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: Specifies the buffer. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering (full buffer)

3), stdin, stdout, stderr respectively represents the standard input, output, error handle of the program. They can be pipe, file descriptor or file object, or set to none, which means inheriting from the parent process.

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

5), Close_sfs: under the Windows platform, if Close_fds is set to true, the newly created child process 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 error (stdin, stdout, stderr) of child processes.

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

7), CWD to set the current directory of the child process

8), env is a dictionary type that specifies the environment variables for a child process. If env = None, the environment variables of the child process are inherited from the parent process.
Universal_newlines: Under different operating systems, text line breaks are not the same. such as: Under Windows with '/r/n ' for Exchange, and Linux under the '/n '. If this parameter is set to True,python uniform, these newline characters are treated as '/n '. Startupinfo and Createionflags are only used under Windows, and they are passed to the underlying CreateProcess () function, which sets some 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 only valid under Windows , they will be passed to the underlying CreateProcess () function to set some 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 (): waits for the child process to end. Sets and returns the ReturnCode property.

3), Popen.communicate (input=none): interacts with the child process. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters that are sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through the process's stdin, 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 stdout and stderr to pipe.

4), popen.send_signal (signal): sends a signal to the child process.

5), Popen.terminate (): Stop (stop) child process. Under the Windows platform, this method will call Windows API TerminateProcess () to end the child process.

6), Popen.kill (): kills 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 policy child process send instruction. 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 policy child process send instruction. 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 policy child process send instruction. 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 finished yet.

12), Subprocess.call (*popenargs, **kwargs): Run the command. The function waits until the child process finishes running and returns the ReturnCode of the process. The first example of this article demonstrates the call function. You can use this function to create a child process if it does not need to interact.

13), Subprocess.check_call (*popenargs, **kwargs): As with Subprocess.call (*popenargs, **kwargs) functions, 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 your program

Can write like this

The code is as follows:


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

You can do that.

The code is as follows:


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


The difference between the two is that the former is non-blocking, and the main program runs in parallel, the latter must wait for the command to complete, if you want the former programming blocking can be

The code is as follows:


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

Program returns run results

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

The code is 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-JEKYLL.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 ten 15:27 c\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9c\ x88 14:35 d3\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9n ', None)

It will return a tuple: (Stdoutdata, Stderrdata)

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

The code is 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-JEKYLL.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 ten 15:27 c\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9c\ x88 14:35 d3\ndrwxrwxr-x 3 limbo limbo 4096 9\xe6\x9n '

The former can achieve more interactions, such as stderr and stdin, but the definition popen (stdin=subprocess) is implemented when Popen is called earlier. PIPE, Stderr=subprocess)

Input to Child process

The code is as follows:


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

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


Subprocess. PIPE

The code is 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

This is actually the process

The code is 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 finishes.

Subprocess. Pipe actually provides a buffer for text flow. 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 finishes.

  • 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.