Some examples of how Python process class subprocess _python

Source: Internet
Author: User

Subprocess. Popen is used to create child processes.

1) Popen initiates a new process to execute in parallel with the parent process, and the default parent process does not wait for the new process to end.

Copy Code code as follows:

Def testpopen ():
Import subprocess
P=subprocess. Popen ("dir", Shell=true)
For I in range (250):
Print ("Other things")

2 The P.wait function causes the parent process to wait for the newly created process to complete, and then to continue the other tasks of the parent process. The return value of the new process can be obtained in the p.returncode at this time.

Copy Code code as follows:

Def testwait ():
Import subprocess
Import datetime
Print (Datetime.datetime.now ())
P=subprocess. Popen ("Sleep", shell=true)
P.wait ()
Print (P.returncode)
Print (Datetime.datetime.now ())

3 The P.poll function can be used to detect whether a newly created process is finished.

Copy Code code as follows:

Def testpoll ():
Import subprocess
Import datetime
Import time
Print (Datetime.datetime.now ())
P=subprocess. Popen ("Sleep", shell=true)
t = 1
while (T <= 5):
Time.sleep (1)
P.poll ()
Print (P.returncode)
T+=1
Print (Datetime.datetime.now ())

4) P.kill or p.terminate is used to end the creation of a new process that is equivalent to calling TerminateProcess () on a Windows system, which is equivalent to sending signals sigterm and Sigkill on a POSIX system.

Copy Code code as follows:

Def testkillandterminate ():
P=subprocess. Popen ("notepad.exe")
t = 1
while (T <= 5):
Time.sleep (1)
T +=1
P.kill ()
#p. Terminate ()
Print ("New process was killed")

5 P.communicate can interact with the new process, but must redirect the pipe when the popen is constructed.

Copy Code code as follows:

Def testcommunicate ():
Import subprocess
cmd = "dir"
P=subprocess. Popen (cmd, Shell=true, stdout=subprocess.) PIPE, Stderr=subprocess. STDOUT)
(Stdoutdata, Stderrdata) = P.communicate ()

If P.returncode!= 0:
Print (cmd + "Error!")
#defaultly The return stdoutdata are bytes, need convert to STR and UTF8
for R in str (stdoutdata,encoding= ' UTF8 '). Split ("\ n"):
Print (R)
Print (P.returncode)


Def TestCommunicate2 ():
Import subprocess
cmd = "dir"
#universal_newlines =true, it means by text way to open stdout and stderr
p = subprocess. Popen (cmd, shell=true, Universal_newlines=true, stdout=subprocess. PIPE, Stderr=subprocess. STDOUT)
CurLine = P.stdout.readline ()

while (CurLine!= ""):
Print (CurLine)
CurLine = P.stdout.readline ()
P.wait ()
Print (P.returncode)

6 The Call function can be considered to be a popen and wait, directly passing the command line to execute, and returning the command line's exit code.

Copy Code code as follows:

Def testcall ():
Retcode = Subprocess.call ("C:\\test.bat")
Print (Retcode)

7 Subprocess.getoutput and Subprocess.getstatusoutput, basically equivalent to the Subprocess.call function, but can return output, or at the same time return exit code and output.

Unfortunately, it doesn't seem to work on the Windows platform, and there are the following errors on Windows: ' {' is not recognized as a internal or external command, operable program or batch File.

Copy Code code as follows:

Def testgetoutput ():
OUTP = Subprocess.getoutput ("Ls-la")
Print (OUTP)

Def testgetstatusoutput ():
(status, OUTP) = Subprocess.getstatusoutput (' Ls-la ')
Print (status)
Print (OUTP)

8) Summary

Popen argument, the first is a string (or it can be multiple unnamed parameters), a parameter that indicates the command and command you want to execute; shell=true, which means that the incoming command you have in front of you will execute under the shell, if your command is an executable file or a bat, You do not need to specify this parameter; stdout=subprocess. Pipe is used to redirect the output of a new process, stderr=subprocess. StdOut redirects the error output of the new process to stdout,stdin=subprocess. Pipe is used to redirect the input of the new process; universal_newlines=true means to open stdout and stderr in text.

Other modules not recommended for use:

Os.system
os.spawn*
os.popen*
popen2.*
commands.*

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.