Some examples of how Python process classes subprocess

Source: Internet
Author: User
Subprocess. Popen is used to create child processes.

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

Copy the 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 finish running before continuing with other tasks of the parent process. You can now get the return value of the new process in P.returncode.

Copy the 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 has ended.

Copy the 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, which is equivalent to calling TerminateProcess () on a Windows system and is equivalent to sending signals sigterm and Sigkill on a POSIX system.

Copy the 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 the pipeline must be redirected at Popen construction time.

Copy the 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 is 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 the text-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 thought of as the popen and wait, directly to the call function to execute the command line, the command line exit code returned.

Copy the Code code as follows:


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

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

Unfortunately, it seems that you cannot use the Windows platform with the following error on Windows: ' {' is not recognized as a internal or external command, operable program or batch File.
Copy the 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 parameters, the first is a string (or can also be a number of non-named parameters), indicating the parameters of the command and command you want to execute, followed by a named argument, Shell=true, which indicates that your previous incoming command will be executed under the shell, if your command is an executable file or bat, You do not need to specify this parameter; stdout=subprocess. The pipe is used to redirect the output of the new process, stderr=subprocess. StdOut redirects the error output of the new process to stdout,stdin=subprocess. The pipe is used to redirect the input of the new process; universal_newlines=true indicates that stdout and stderr are opened in text mode.

Other deprecated modules:

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.