Python subprocess module summary, pythonsubprocess

Source: Internet
Author: User

Python subprocess module summary, pythonsubprocess

Subprocess is intended to replace several other old modules or functions, such as OS. system OS. spawn * OS. popen * popen2. * commands .*
The simplest use of subprocess is to call shell commands. In addition, you can call programs and interact with stdout, stdin, and stderr.

Subprocess main class

Copy codeThe 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). argsIt can be a string or a sequence type (such as list and tuples), used to specify the executable files and their parameters of a process. 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.

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

3), stdin, stdout, stderrIndicates 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.

4). preexec_fnIt is valid only on Unix platforms and is used to specify a callable object, which will be called before the sub-process runs.

5) Close_sfs:On windows, if close_fds is set to True, the newly created child process does 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 ).

6) shellIf it is set to true, the program will be executed through shell.

7). cwdUsed to set the current directory of the sub-process

8), envIt 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: 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. Startupinfo and createionflags 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.

9) startupinfo and createionflags are only valid in windows.They will be passed to the underlying CreateProcess () function to set attributes of sub-processes, such as the appearance of the main window and the priority of processes.

Popen Method

1) Popen. poll ():Used to check whether the sub-process has ended. Set and return the returncode attribute.

2) Popen. wait ():Wait until the child process ends. Set and return the returncode attribute.

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

4), Popen. send_signal (signal ):Sends signals to sub-processes.

5), Popen. terminate ():Stop the sub-process. On windows, this method calls the Windows API TerminateProcess () to end the child process.

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

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

8), 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.

9), 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.

10), Popen. pid:Obtain the ID of the sub-process.

11), Popen. returncode:Obtain the return value of a process. If the process has not ended, None is returned.

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

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

All of the above are copied

Run other programs or shells in the program

Write like this
Copy codeThe Code is as follows:
Subprocess. Popen ('script/shell', shell = True)

You can also
Copy codeThe Code is as follows:
Subprocess. call ('script/shell', shell = True)

The difference between the two is that the former is non-blocking and runs in parallel with the main program. The latter must wait for the command to be executed. If you want the former to program blocking, you can do this.
Copy codeThe Code is as follows:
S = subprocess. Popen ('script/shell', shell = True)
S. wait ()

The program returns the running result.

Sometimes we need the results returned by the program. You can do this.
Copy codeThe 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 808 7 \ xe6 \ x9c \ x88 6 ↓ \ MCM wx ------ 2 limbo 4096 8 \ xe6 \ x9c \ x88 15 arg \ MCM wx ------ 2 limbo 4096 8 \ xe6 \ x9c \ x88 7 argv \ NDRC wxrwxr-x 2 limbo limbo 4096 9 \ xe6 \ x9c \ x88 10 c \ NDRC wxrwxr-x 3 limbo 4096 9 \ xe6 \ x9c \ x88 11 d3 \ NDRC wxrwxr-x 3 limbo 4096 9 \ xe6 \ x9n ', none)

It returns a tuples (stdoutdata, stderrdata)

Subprocess has another simpler method, with the same effect, it returns stdout
Copy codeThe 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 808 7 \ xe6 \ x9c \ x88 6 \ NDRC wx ------ 2 limbo 4096 8 \ xe6 \ x9c \ x88 15 arg \ NDRC wx ------ 2 limbo 4096 8 \ xe6 \ x9c \ x88 7 argv \ NDRC wxrwxr-x 2 limbo 4096 9 \ xe6 \ x9c \ x88 10 c \ NDRC wxrwxr-x 3 limbo 4096 9 \ xe6 \ x9c \ x88 11 35 d3 \ NDRC wxrwxr-x 3 limbo 4096 9 \ xe6 \ x9n'

The former can implement more interactions, such as stderr and stdin, but Popen (stdin = subprocess. PIPE, stderr = subprocess) must be defined When Popen is called)

Input to sub-process

Copy codeThe Code is as follows:
Import subprocess
Child = subprocess. Popen (["cat"], stdin = subprocess. PIPE)
Child. communicate ("vamei ")

() If it is not null, it is written to subprocess. PIPE. If it is null, it is read from subprocess. PIPE.


Subprocess. PIPE
Copy codeThe 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.
Copy codeThe 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. This method blocks the parent process until the child process is completed.

Subprocess. PIPE actually provides a cache for text streams. Until the communicate () method reads the text in PIPE from PIPE. note that communicate () is a method of the Popen object. This method blocks the parent process until the child process is completed.


Problems with the subprocess module of python

Processing = open (R 'd: \ tmp. log', 'weight ')
Subprocess. Popen (['ipconfig', 'all'], standard output = handle)
..

A special usage of python's subprocess module Popen in windows

Def getmask ():
Command = 'for/f "delims =: tokens = 2" % I in (\ 'ipconfig ^ | findstr subnet mask \') do echo % I'
Popen (command, shell = True)

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.