The subprocess of Python

Source: Internet
Author: User
Tags terminates

Website Description: https://docs.python.org/3/library/subprocess.html

popen (): [[email protected] scripts]# cat sub_popen.py #!/usr/bin/ Python#coding=utf8import subprocesschild = subprocess. Popen ([' ls ', '-l '],shell=true) print (type (child)) print (' parent ') [[email protected] scripts]# python sub_ popen.py <class ' subprocess. Popen ' >parentstu_subprocess.py sub_popen.py if the shell is not added, use the default: [[email protected] scripts]# cat sub_popen.py #!/usr/bin/python#coding=utf8import subprocesschild = subprocess. Popen ([' ls ', '-l '],shell=false) shell parameter defaults to Falseprint (type (child)) print (' parent ') [[email protected] scripts]# Python sub_popen.py <class ' subprocess. Popen ' >parenttotal 8-rw-r--r--1 root root (15:26 stu_subprocess.py-rw-r--r--1 root root 136) 15:41 Su B_popen.pypopen does not block the parent process from running, Popen starts the new process in parallel with the parent process, and the default parent process does not wait for the new process to end. 
[[email protected] scripts]# cat Test_subprocess.py#!/usr/bin/python#coding=utf8 def TestPopen (): Import SUBPROCESSP = subprocess. Popen ([' ls ', '-l '],shell=true) for I in range (5):p rint ("Other things") print (Testpopen ()) [[email protected] scripts]# python test_subprocess.pyother thingsother thingsother thingsother thingsother thingsNonestu_subprocess.py sub_call.py sub_check_output.py sub_popen.py sub_run.py test_subprocess.py [[email protected] scripts]# cat Test_ Subprocess1.py#!/usr/bin/python#coding=utf8 wait (): Blocks the parent process, waits for the child process to run to end before continuing to run the parent process def testwait (): Import Subprocessimport Datetimeprint (Datetime.datetime.now ()) p = subprocess. Popen (' Sleep ', shell=true) p.wait () wait () is blocking the run of the parent process, waiting for the child process to finish running before continuing to run the parent process print (P.returncode) print ( Datetime.datetime.now ()) testwait () [[email protected] scripts]# python test_subprocess1.py2017-08-21 16:49:15.0616760 when the child process finishes running, return code to 02017-08-21 16:49:25.066657 poll (): Determine if the child process is over [[email protected] scripts]# Cat Test_subprocess2.py#!/usr/bin/pytHon#coding=utf8 def testwait (): Import Subprocessimport Datetime,timeprint (Datetime.datetime.now ()) p = subprocess. Popen (' Sleep ', shell=true) sub-process to sleep 10 seconds t = 1while (T <= 5): Time.sleep (1) p.poll () Execute the judging subprocess, it took 5 seconds to print (p.returncode) T = T + 1print (Datetime.datetime.now ()) testwait () [[email protected] scripts]# python test_subprocess2.py2017-08-21 16:56:33.672417nonenonenonenonenone2017-08-21 16:56:38.684795 Kill () or terminate (): Kill child Process [[email protected] scripts]# Cat Test_subprocess3.py#!/usr/bin/python#coding=utf8 def testkillandterminate (): Import Subprocessimport Datetime,timeprint (Datetime.datetime.now ()) p = subprocess. Popen (' Sleep ', shell=true) t = 1while (T <= 5): Time.sleep (1) t = t + 1p.kill () print (Datetime.datetime.now ()) Testkilla Ndterminate () [[email protected] scripts]# python test_subprocess3.py2017-08-21 17:03:16.3155312017-08-21 17:03:21.329266 can see that the child process is only running for 5 seconds
[[email protected] scripts]# cat sub_popen.py #!/usr/bin/python#coding =utf8import subprocesschild = subprocess. Popen ([' ls ', '-l '],shell=false) child.wait () blocks the parent process until the child process runs complete print (type (child)) print (' parent ') [[Email prot ected] scripts]# python sub_popen.py total 12-rw-r--r--1 root root 15:26 stu_subprocess.py-rw-r--r--1 root ro OT 135 15:47 sub_call.py-rw-r--r--1 root root 149 15:47 sub_popen.py<class ' subprocess. Popen ' >parent can see the child process running first, and finally the parent process, waiting for the child process to run, and then running the parent process in addition to wait () is as follows: Child.poll () # Check child process Status Child.kill () # Terminates a subprocess child.send_signal () # sends a signal to a child process child.terminate () # The PID of the child process that terminates the child process is stored in the standard input, standard output, and standard error of the CHILD.PID child process, respectively, with the following attributes: Child.stdinchild.stdoutchild.stderr 
subprocess. Pipe actually provides a buffer for text flow. The child's stdout outputs the text to the buffer and then prints out the contents of the buffer: [[email protected] scripts]# cat sub_popen.py #!/usr/bin/python#coding= Utf8import subprocesschild = subprocess. Popen ([' ls ', '-l '],shell=false,stdout=subprocess. PIPE) Print (Child.stdout.read () decode (' Utf-8 ') prints the buffer content, because it is in bytes format, transcoding print (' parent ') [[email protected] scripts]# python sub_popen.py total 16-rw-r--r--1 root root-15:26 stu_subprocess.py-rw-r--r--1 root root 148 15:53 sub_call.py-rw-r--r--1 root root 183 16:07 sub_popen.py-rw-r--r--1 root root 147-15:56 Sub_ru N.pyparent 
Communicate () 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. [[email protected] scripts]# cat sub_popen.py #!/usr/bin/python#coding=utf8import subprocesschild = subprocess. Popen ([' ls ', '-l '],shell=false,stdout=subprocess. PIPE) #print (Child.stdout.read () decode (' Utf-8 ')) print (Child.communicate ()) returns the standard output, the Tupleprint of the standard error output (' Parent ') [[email protected] scripts]# python sub_popen.py (b ' Total 16\n-rw-r--r--1 root root: 15:26 stu_subprocess. py\n-rw-r--r--1 root root 148 15:53 sub_call.py\n-rw-r--r--1 root root 211 16:11 sub_popen.py\n-rw-r--r-- 1 root root 147 15:56 sub_run.py\n ', none) None is the standard error output result the parent can see the output of the child process content, and then the father process, communicate () is a method of the Popen object, This method blocks the parent process until the child process finishes [[Email protected]cle scripts]# cat sub_popen.py #!/usr/bin/python#codinG=utf8import subprocesschild1 = subprocess. Popen ([' Cat ', '/etc/passwd '],shell=false,stdout=subprocess. PIPE) child2 = subprocess. Popen ([' grep ', ' 0:0 '],stdin=child1.stdout, stdout=subprocess. PIPE) # subprocess. Pipe actually provides a buffer for text flow. The child1 stdout the text out to the buffer, and then Child2 's stdin reads the text from the pipe. The output text of the child2 is also stored in the pipe until the communicate () method reads the text from the pipe. Out,err = Child2.communicate () because communicate () returns a meta-ancestor print (out) paper prints out the standard output content print (' parent ') [[email protected] s cripts]# python sub_popen.py B ' root:x:0:0:root:/root:/bin/bash\n ' parentchild1.stdout-->subprocess. Pipechild2.stdin<--subprocess. Pipechild2.stdout-->subprocess. Pipe uses communicate () to interact: [[email protected] scripts]# cat stu_subprocess.py #!/usr/bin/python#coding= Utf8import subprocesschild1 = subprocess. Popen ([' Python '],stdin=subprocess. Pipe,stdout=subprocess. Pipe,stderr=subprocess. PIPE) Out,err = child1.communicate (b ' Print ("Hello") \nexit () ') continues to enter information for the child process # starts a subprocess and then controls its input and output print (Out.decode (' Utf-8 ') print (' parent ') [[EMAIL&NBSP;PRotected] scripts]# python stu_subprocess.py helloparent 
[[email protected] scripts]# cat sub_popen2.py #!/usr/bin/python# Coding=utf8import subprocess obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE) obj.stdin.write (b ' Print ("Hello") \ n ') Stdin.write and communicate are exchanged using Obj.stdin.write (b ' Print ("World") ') out, Err = Obj.communicate () print (out) [[email protected] scripts]# python sub_popen2.py b ' hello\nworld\n ' 
Call (): Subprocess.call () parent process waits for child process to complete return exit information (ReturnCode, equivalent to Linux exit code) [[email protected] scripts]# cat sub_ call.py #!/usr/bin/python#coding=utf8import subprocesschild = subprocess.call ([' ls ', '-l '],shell=false) print (Type (  Child)) print (' parent ') [[[email protected] scripts]# python sub_call.py total 12-rw-r--r--1 root root 21 15:26 stu_subprocess.py-rw-r--r--1 root root 135 15:45 sub_call.py-rw-r--r--1 root root 136 15:41 sub_popen.py& The lt;class ' int ' > Call function returns the intparent calling function to see that the child process is blocking the run of the main process, running the child process first, and finally the main process [[email protected] Scri pts]# Cat sub_call.py #!/usr/bin/python#coding=utf8import subprocesschild = subprocess.call ([' ls ', '-l '],shell=False)  Print (type) print (child)----->returncodeprint (' parent ') [[email protected] scripts]# python sub_call.py Total 12-rw-r--r--1 root root 15:26 stu_subprocess.py-rw-r--r--1 root root 148 21 15: sub_call.py-rw-r--r--1 root root 149 2115:47 sub_popen.py<class ' int ' >0parentsubprocess.call (*popenargs, **kwargs): Run the command. The function waits until the child process finishes running and returns the ReturnCode of the process. You can use this function to create a child process if it does not need to interact. The call function returns ReturnCode, which is the type of int, depending on the shell type, you can change the args type of the incoming call function: [[email protected] scripts]# cat sub_call.py #!/ Usr/bin/python#coding=utf8import subprocesschild = Subprocess.call ("Ls-l", shell=true) print (type (child)) print (chil D) the print (' parent ') shell=true parameter will let Subprocess.call accept a variable of string type as a command, and call the shell to execute the string when Shell=false is, Subprocess.call only accepts array variables as commands, and takes the first element of the array as a command, all remaining as arguments to the command. [[email protected] scripts]# python sub_call.py total 40-rw-r--r--1 root root--15:26 stu_subprocess.py-rw- r--r--1 root root 143 17:22 sub_call.py-rw-r--r--1 root root 143 16:33 sub_check_output.py-rw-r--r--1 roo  T root 162 17:17 sub_getoutput.py-rw-r--r--1 root root 279 16:17 sub_popen.py-rw-r--r--1 root root 148 16:29 sub_run.py-rw-r--r--1 root root 257 16:53 test_subprocess1.py-rw-r--r--1 root root 340 16:52 test_subprocess2.py-rw-r--r--1 root root 332 17:03 test_subprocess3.py-rw-r--r--1 root root 183 16:44 test_subprocess.py<class ' int ' >0parent so when the shell defaults to False, the value that args passes in must be a list, not a strfrom subprocess import Call import Shlex cmd = "Cat test.txt; RM test.txt "Call (cmd, shell=true) Shell description: https://zhidao.baidu.com/question/651286079254739125.html
3.5 New Run (): Class subprocess. Completedprocessthe return value from Run (), representing a process, which has finished. [[email protected] scripts]# cat sub_run.py #!/usr/bin/python#coding=utf8import subprocesschild = Subprocess.run ([' ls ', '-l '],shell=false) print (type (child)) print (child) print (' parent ') [[email protected] scripts]# python sub_run.py Total 16-rw-r--r--1 root root 15:26 stu_subprocess.py-rw-r--r--1 root root 148 15:53 Sub_ca ll.py-rw-r--r--1 root root 149 15:47 sub_popen.py-rw-r--r--1 root root 147 15:56 sub_run.py<class ' SUBP Rocess. Completedprocess ' >completedprocess (args=[' ls ', '-l '], returncode=0) parent 
check_output (): [[email protected] scripts]# cat sub_check_output.py#! /usr/bin/python#coding=utf8import subprocesschild = subprocess.check_output ([' ls ', '-l '],shell=false) print (Type ( ) print (child) print (' parent ') [[[email protected] scripts]# python sub_check_output.py<class ' bytes ' >b ' Total 20\n-rw-r--r--1 root root 15:26 stu_subprocess.py\n-rw-r--r--1 root root 148 15:53 sub_cal l.py\n-rw-r--r--1 root root 156 16:26 sub_check_output.py\n-rw-r--r--1 root root 279 16:17 sub_popen.py\n- rw-r--r--1 root root 147 15:56 sub_run.py\n ' parent [[email protected] scripts]# cat sub_check_output.py#!/usr /bin/python#coding=utf8import subprocesschild = subprocess.check_output ([' ls ', '-l '],shell=false) print (Type (child) Print (' parent ') [[[email protected] scripts]# python sub_check_output.py<class ' bytes ' > The parent did not print the contents of the child process after it was run 
Subprocess.getoutput (CMD), returns a string return output (stdout and stderr) of executing cmd in a shell. [[email protected] scripts]# python sub_getoutput.py <class ' str ' >stu_subprocess.pysub_call.pysub_check_ Output.pysub_getoutput.pysub_popen.pysub_run.pytest_subprocess1.pytest_subprocess2.pytest_subprocess3.pytest_ Subprocess.py[[email protected] scripts]# cat sub_getoutput.py #!/usr/bin/python#coding=utf8import Subprocessdef testgetoutput (): OUTP = Subprocess.getoutput (["LS", "-l"]) list print (type (OUTP)) print (OUTP) Testgetou Tput () [[email protected] scripts]# cat sub_getoutput.py #!/usr/bin/python#coding=utf8import subprocessdef Testgetoutput (): OUTP = Subprocess.getoutput ("ls-l") string print (Type (OUTP)) print (OUTP) testgetoutput () [[EMAIL&NB sp;protected] scripts]# python sub_getoutput.py <class ' str ' >total 40-rw-r--r--1 root root-15:26 stu_sub process.py-rw-r--r--1 root root 148 15:53 sub_call.py-rw-r--r--1 root root 143 21 16:sub_check_output.py-rw-r--r--1 root root 162 17:17 sub_getoutput.py-rw-r--r--1 root root 279 16:17 sub_ popen.py-rw-r--r--1 root root 148 16:29 sub_run.py-rw-r--r--1 root root 257 16:53 test_subprocess1.py-rw-r --r--1 root root 340 16:52 test_subprocess2.py-rw-r--r--1 root root 332 17:03 test_subprocess3.py-rw-r--r- -1 root root 183 16:44 test_subprocess.py
#接收字符串格式命令, returns the tuple form, the 1th element is the execution state, the 2nd is the command result >>> subprocess.getstatusoutput (' ls-l ')     (0, ' total 40\ n-rw-r--r--1 root root 15:26 stu_subprocess.py\n-rw-r--r--1 root root 143 17:22 sub_call.py\n-rw-r--r-  -1 root root 143 16:33 sub_check_output.py\n-rw-r--r--1 root root 162 17:17 sub_getoutput.py\n-rw-r--r--1 Root root 279 16:17 sub_popen.py\n-rw-r--r--1 root root 148 16:29 sub_run.py\n-rw-r--r--1 root root 257 A UG 16:53 test_subprocess1.py\n-rw-r--r--1 root root 340 16:52 test_subprocess2.py\n-rw-r--r--1 root root 332 A UG 17:03 test_subprocess3.py\n-rw-r--r--1 root root 183 16:44 test_subprocess.py ')

The subprocess of Python

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.