This article mainly introduces some examples of subprocess operations for python processes. This article describes the actual operation examples of Popen, wait, poll, kill, communicate and other methods, for more information, see subprocess. popen is used to create sub-processes.
1) Popen starts a new process and runs it in parallel with the parent process. by default, the parent process does not wait until the new process ends.
The code is 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 until the new process finishes running and then continue other tasks of the parent process. In this case, the return value of the new process can be obtained in p. returncode.
The code is as follows:
Def TestWait ():
Import subprocess
Import datetime
Print (datetime. datetime. now ())
P = subprocess. Popen ("sleep 10", shell = True)
P. wait ()
Print (p. returncode)
Print (datetime. datetime. now ())
3) the p. poll function can be used to check whether the newly created process has ended.
The code is as follows:
Def TestPoll ():
Import subprocess
Import datetime
Import time
Print (datetime. datetime. now ())
P = subprocess. Popen ("sleep 10", 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 created new process. in windows, it is equivalent to calling TerminateProcess (). In posix, it is equivalent to sending signals SIGTERM and SIGKILL.
The code is 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 during popen construction.
The code is 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 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 as a sub-assembly of popen and wait. it directly transmits the command line to be executed to the call function and returns the exit code of the command line.
The code is as follows:
Def TestCall ():
Retcode = subprocess. call ("c: \ test. bat ")
Print (retcode)
7) subprocess. getoutput and subprocess. getstatusoutput are basically equivalent to subprocess. call functions, but can return output or both the exit code and output.
Unfortunately, it seems that it cannot be used on windows. the following error occurs on windows: '{' is not recognized as an internal or external command, operable program or batch file.
The code is 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
The parameter of popen. The first parameter is a string (or multiple non-named parameters can also be used), indicating the parameters of the command and command to be executed. the following parameters are named parameters; shell = True, which indicates that the previously passed command will be executed in shell. if your command is an executable file or bat, you do not need to specify this parameter; stdout = subprocess. 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. PIPE is used to redirect input of new processes. universal_newlines = True indicates to open stdout and stderr in text mode.
Other modules Not recommended:
OS. system
OS. spawn *
OS. popen *
Popen2 .*
Commands .*