After being familiar with the qprocess of Qt, looking back at the Python subprocess finally did not feel as scary as before.
Like Qprocess, Subprocess's goal is to start a new process and communicate with it.
subprocess. Popen
This module mainly provides a class Popen:
Class subprocess. Popen (args,
bufsize=0,
executable=none,
stdin=none,
stdout=none,
stderr=none,
preexec_ Fn=none,
Close_fds=false,
shell=false,
cwd=none,
env=none,
Universal_newlines=false,
Startupinfo=none,
creationflags=0)
This pile of stuff really freaks me out:
Subprocess. Popen (["Gedit", "Abc.txt"])
subprocess. Popen ("Gedit abc.txt")
Of these two, the latter will not work. Because if it is a string, it must be the path to the program. (Consider the UNIX API function exec, accept a list of strings)
But the following can work
Subprocess. Popen ("Gedit abc.txt", shell=true)
This is because it is equivalent
Subprocess. Popen (["/bin/sh", "-C", "Gedit Abc.txt"])
It all became the parameters of sh, it doesn't matter.
Under Windows, the following can work
Subprocess. Popen (["Notepad.exe", "Abc.txt"])
subprocess. Popen ("notepad.exe abc.txt")
This is because the API function under Windows CreateProcess accepts a string. Even parameters in the form of lists need to be merged into strings before being passed to API functions.
Similar to the above
Subprocess. Popen ("notepad.exe abc.txt" shell=true)
Equivalent to
Subprocess. Popen ("cmd.exe/c" + "notepad.exe abc.txt" shell=true)
subprocess.call*
The module also provides several convenience functions (which in itself is a good example of popen usage)
Call () executes the program and waits for it to complete
def call (*popenargs, **kwargs): Return
Popen (*popenargs, **kwargs). Wait ()
Check_call () invokes the preceding call and throws an exception if the return value is Non-zero
def check_call (*popenargs, **kwargs):
retcode = Call (*popenargs, **kwargs)
if retcode:
cmd = Kwargs.get (" Args ")
raise Calledprocesserror (Retcode, cmd) return
0
Check_output () executes the program and returns its standard output
def check_output (*popenargs, **kwargs):
process = Popen (*popenargs, Stdout=pipe, **kwargs)
output, Unused_ Err = Process.communicate ()
retcode = Process.poll ()
if retcode:
cmd = Kwargs.get ("args")
raise Calledprocesserror (Retcode, cmd, output=output) return
output
Popen objects
This object provides a number of method functions available. And we've already used the Wait ()/poll ()/communicate ()