Introduction and use of subprocess module

Source: Internet
Author: User

One, subprocess and commonly used encapsulation functions
When we run Python, we are all creating and running a process. Like the Linux process, a process can fork a child process and let the child process exec another program. In Python, we fork a child process through the subprocess package in the standard library and run an external program.
The subprocess package defines a number of functions that create child processes, each of which creates child processes in different ways, so we can choose one to use as needed. In addition, Subprocess provides some tools for managing standard streams and pipelines (pipe) to use text communication between processes.

Subprocess.call ()
Parent process waits for child process to complete
Return exit information (ReturnCode, equivalent to Linux exit code)

Subprocess.check_call ()
Parent process waits for child process to complete
Returns 0
Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, this object contains the ReturnCode property, which can be try...except ... To check

Subprocess.check_output ()
Parent process waits for child process to complete
Returns the output of the child process to the standard output
Check the exit information, and if ReturnCode is not 0, cite error subprocess. Calledprocesserror, which contains the ReturnCode property and the output property, outputs a result of the standard output, available try...except ... To check.

First, Introduction

Subprocess was first introduced in version 2.4. Used to generate child processes, and to connect their input/output/errors through pipelines, and to get their return values.

Subprocess is used to replace multiple old modules and functions:

    • Os.system

    • os.spawn*

    • os.popen*

    • popen2.*

    • commands.*

When we run Python, we are all creating and running a process where a process in Linux can fork a subprocess and have the child process exec another program. In Python, we fork a child process through the subprocess package in the standard library and run an external program. The subprocess package defines a number of functions that create child processes, each of which creates sub-processes in different ways, and we can choose one to use as needed. In addition, Subprocess provides some tools for managing standard streams and pipelines (pipe) to use text communication between processes.

Second, the use of the old module

1.os.system ()

Executes the operating system command, outputs the result to the screen, returning only the command execution state (0: success, not 0: failed)

Import os>>> a = Os.system ("df-th") Filesystem     Type   Size  used Avail use% mounted On/dev/sda3      Ext4   1.8T  436G  1.3T  26%/tmpfs          tmpfs   16G     0   16G   0%/dev/shm/dev/sda1      Ext4   190M  118M   63M  66%/boot>>> A0         # 0 indicates execution succeeded # command to execute error >>> res = Os.system (" List ") Sh:list:command not found>>> res32512       # return non 0 means execution error

  

2. Os.popen ()

The command that executes the operating system saves the results in memory and can be read by the read () method

Import os>>> res = Os.popen ("Ls-l") # Saves the results in memory >>> print Res<open file ' ls-l ', mode ' R ' at 0X7F02D24 9c390># read () content >>> print res.read () total 267508-rw-r--r--  1 root    260968 Jan  2016 ALIIM.EXE-RW-------. 1 root root      1047  anaconda-ks.cfg-rw-r--r--  1 root root   9130958 Nov 18< c7/>2015 apache-tomcat-8.0.28.tar.gz-rw-r--r--  1 root root         0 Oct  badblocks.logdrwxr-xr-x  5 Root root      4096  certs-builddrwxr-xr-x  2 root root      4096 Jul  5 16:54 desktop-rw-r--r--  1 root root      2462 Apr 11:50 Face_24px.ico

  

Three, subprocess module

1, Subprocess.run ()

>>> Import subprocess# Python parse the list of each parameter of the incoming command >>> subprocess.run (["DF", "-H"]) Filesystem            Size  used Avail use% mounted on/dev/mapper/volgroup-logvol00                      289G   70G  204G  26%/tmpfs                  64G     0   64G   0%/dev/shm/dev/sda1             283M   27M  241M  11%/bootcompletedprocess (args=[' df ', '-h '), returncode=0) # needs to be given to the Linux shell to parse itself: the incoming command string,shell=true>>> subprocess.run ("df-h|grep/dev/sda1", shell= True)/dev/sda1             283M   27M  241M  11%/bootcompletedprocess (args= ' df-h|grep/dev/sda1 ', ReturnCode =0)

  

2, Subprocess.call ()

Executes the command, returns the result and execution status of the command, 0 or not 0

>>> res = Subprocess.call (["LS", "-l"]) Total usage 28-rw-r--r--  1 root root     0 June  10:28 1drwxr-xr-x  2 Root root  4096 June  17:48 _1748-rw-------. 1 root root  1264 April  20:51 anaconda-ks.cfgdrwxr-xr-x  2 Root root  4096 May  14:45 monitor-rw-r--r--  1 root root 13160 May   9 13:36 npm-debug.log# command execution status >> ;> Res0

  

3, Subprocess.check_call ()

Execute command, return result and status, normal 0, execute error throws exception

>>> subprocess.check_call (["LS", "-l"]) Total usage 28-rw-r--r--  1 root root     0 June  10:28 1drwxr-xr-x  2 root root  4096 June  17:48 _1748-rw-------. 1 root root  1264 April  20:51 anaconda-ks.cfgdrwxr-xr-x  2 root root  4096 May  14:45 monitor-rw-r--r--  1 root root 13160 May   9 13:36 Npm-debug.log0>> ;> Subprocess.check_call (["LM", "-l"]) Traceback (most recent call last):  File ' <stdin> ', line 1, in < module>  File "/usr/lib64/python2.7/subprocess.py", line 537, in Check_call    retcode = Call (*popenargs, * * Kwargs)  File "/usr/lib64/python2.7/subprocess.py", line 524, on call    return Popen (*popenargs, **kwargs). Wait ()  file "/usr/lib64/python2.7/subprocess.py", line 711, in __init__    errread, errwrite)  file "/usr/  lib64/python2.7/subprocess.py ", line 1327, in _execute_child    raise Child_exceptionoserror: [Errno 2] No such file or Directory

  

4, Subprocess.getstatusoutput ()

Accepts the command as a string, returns the result as a tuple, the first element is the command execution state, and the second executes the result

#执行正确 >>> subprocess.getstatusoutput (' pwd ') (0, '/root ') #执行错误 >>> subprocess.getstatusoutput (' PD ') (127, '/bin/sh:pd:command not found ')

  

5, Subprocess.getoutput ()

Accept the command as a string and put back the execution result

>>> subprocess.getoutput (' pwd ') '/root '

  

6, Subprocess.check_output ()

Executes the command, returning the result of the execution, rather than printing

>>> res = subprocess.check_output ("pwd") >>> resb '/root\n ' # results returned in bytes

  

Four, subprocess. Popen ()

In fact, the above subprocess use of methods, are to subprocess. Popen package, let's take a look at this popen method.

1, stdout

Standard output

>>> res = subprocess. Popen ("Ls/tmp/yum.log", Shell=true, stdout=subprocess. PIPE)  # Use pipe >>> res.stdout.read ()    # standard output B '/tmp/yum.log\n ' Res.stdout.close ()   # Off

  

2, stderr

Standard error

>>> Import subprocess>>> res = subprocess. Popen ("Lm-l", shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) # Standard output is empty >>> res.stdout.read () b ' #标准错误中有错误信息 >>> res.stderr.read () b '/bin/sh:lm:command not Found\n '

  

Note: All of the standard output mentioned above needs to be equal to subprocess. PIPE, what is this again? Originally this is a pipe, this need to draw a diagram to explain:

4, poll ()

The timing Check command is completed, the execution is completed, the status of the execution result is returned, no execution is completed.

>>> res = subprocess. Popen ("Sleep 10;echo ' Hello '", shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> print (Res.poll ()) none>>> print (Res.poll ()) none>>> print (Res.poll ()) 0

  

5. Wait ()

Wait for command execution to complete and return result status

>>> obj = subprocess. Popen ("Sleep 10;echo ' Hello '", shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> obj.wait () # The middle will always wait 0

  

6, Terminate ()

End Process

Import subprocess>>> res = subprocess. Popen ("Sleep 20;echo ' Hello '", shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> res.terminate ()  # End Process >>> res.stdout.read () b '

7. PID

Gets the process number of the program that currently executes the child shell

Import subprocess>>> res = subprocess. Popen ("Sleep 5;echo ' Hello '", shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) >>> res.pid  # Get the process number 2778 for this Linux shell

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.