Python subprocess Module

Source: Internet
Author: User

Subprocess Module

subprocessthe module allows spawn new processes, connect to their input/output/error pipes, and obtain their return cod Es. This module intends to replace several older modules and functions:

Os.  SystemOS.  Spawn*

The recommended approach to invoking subprocesses are to use the function for all use run() cases it can handle. For cases, the underlying Popen interface can is used directly.

run()The function is added in Python 3.5; If you need to retain compatibility with older versions, see the older High-le Vel API section.

subprocess.run(args, *, Stdin=none, Input=none, Stdout=none, Stderr=none, Shell=false, Timeout=none, Check=false)

Run the command described by args. Wait for command to complete and then return a CompletedProcess instance.

The arguments shown above is merely the most common ones, described below in frequently used arguments (hence the use of Keyword-only notation in the abbreviated signature). The full function signature are largely the same as Popen that of the Constructor-apart from timeout, input and check, AL L The arguments to this function is passed through to that interface.

This does is not a capture stdout or stderr by default. To does so, pass for the PIPE stdout and/or stderr arguments.

The timeout argument is passed To  popen.communicate () . If The timeout expires, the child process is killed and waited for. The timeoutexpired   Exception'll is re-raised after the child process has terminated.

The input argument is passed to and thus to the Popen.communicate() subprocess ' s stdin. If used it must be a byte sequence, or a string if universal_newlines=True . When used, the internal Popen object was automatically created stdin=PIPE with, and the stdin argument could not be used as well.

If check is True, and the process exits with a Non-zero exit code, a CalledProcessError exception would be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

Examples of common subprocess methods

#执行命令, returns the command execution status, 0 or not 0
>>> retcode = Subprocess.call (["LS", "-l"])

#执行命令, if the command result is 0, return normally, otherwise throw an exception
>>> subprocess.check_call (["LS", "-l"])
0

#接收字符串格式命令, returns the tuple form, the 1th element is the execution state, and the 2nd is the command result
>>> subprocess.getstatusoutput (' Ls/bin/ls ')
(0, '/bin/ls ')

#接收字符串格式命令 and returns the result
>>> subprocess.getoutput (' Ls/bin/ls ')
'/bin/ls '

#执行命令, and return the result, note that the result is returned, not printed, and the following example returns to Res
>>> res=subprocess.check_output ([' ls ', '-l '])
>>> Res
B ' Total 0\ndrwxr-xr-x-Alex Staff 408 2 11:05 oldboycrm\n '

#上面那些方法, the bottom layer is the encapsulated subprocess. Popen
Poll ()
Check If child process has terminated. Returns ReturnCode

Wait ()
Wait for the child process to terminate. Returns ReturnCode attribute.


Terminate () Kill the startup process
Communicate () Wait for task to end

stdin Standard input

STDOUT standard output

STDERR standard Error

Pid
The process ID of the child process.

#例子
>>> p = subprocess. Popen ("Df-h|grep disk", stdin=subprocess. Pipe,stdout=subprocess. Pipe,shell=true)
>>> P.stdout.read ()
B '/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14%/\n '

1234567891011 >>> subprocess.run(["ls", "-l"])  # doesn‘t capture outputCompletedProcess(args=[‘ls‘, ‘-l‘], returncode=0)>>> subprocess.run("exit 1", shell=True, check=True)Traceback (most recent call last):  ...subprocess.CalledProcessError: Command ‘exit 1‘returned non-zero exit status 1>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)CompletedProcess(args=[‘ls‘, ‘-l‘, ‘/dev/null‘], returncode=0,stdout=b‘crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n‘)

Call Subprocess.run (...) Is the recommended common method, in most cases it satisfies the requirements, but if you may need to do some complex interaction with the system, you can also use subprocess. Popen (), the syntax is as follows:

12 p =subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)print(p.stdout.read())

Available parameters:

      • The Args:shell command, which can be a string or sequence type (for example: list, tuple)
      • BufSize: Specifies buffering. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering
      • stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively
      • PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run
      • CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.
        Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.
      • Shell: Ibid.
      • CWD: Used to set the current directory of child processes
      • ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.
      • Universal_newlines: Different system line breaks differ, True----agree to use \ n
      • Startupinfo and Createionflags are only valid under Windows
        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, etc.

The commands for terminal input are divided into two types:

    • Input can be output, such as: ifconfig
    • Input to an environment that relies on re-entry, such as: Python

Examples of commands that require interaction

12345678910 import subprocessobj =subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write(‘print 1 \n ‘)obj.stdin.write(‘print 2 \n ‘)obj.stdin.write(‘print 3 \n ‘)obj.stdin.write(‘print 4 \n ‘)out_error_list =obj.communicate(timeout=10)printout_error_list
Subprocess Automatic password entry for sudo
123456789101112131415161718 importsubprocessdefmypass():    mypass =‘123‘#or get the password from anywhere    returnmypass echo =subprocess.Popen([‘echo‘,mypass()],                        stdout=subprocess.PIPE,                        )sudo =subprocess.Popen([‘sudo‘,‘-S‘,‘iptables‘,‘-L‘],                        stdin=echo.stdout,                        stdout=subprocess.PIPE,                        )end_of_pipe =sudo.stdoutprint"Password ok \n Iptables Chains %s" %end_of_pipe.read() 

Python subprocess Module

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.