I. subprocess and common encapsulated Functions
When running python, we are creating and running a process. Like a Linux Process, a process can fork a sub-process and let the sub-process exec another program. In Python, we use the subprocess package in the standard library to fork a sub-process and run an external program.
The subprocess package defines several functions for creating sub-processes. These functions are used to create sub-processes in different ways. Therefore, you can select a sub-process as needed. In addition, subprocess provides some tools for managing standard streams and pipelines to use text communication between processes.
Subprocess. call ()
The parent process waits for the child process to complete.
Returns the exit information (returncode, equivalent to the Linux exit code)
Subprocess. check_call ()
The parent process waits for the child process to complete.
Returns 0.
Check the exit information. If the returncode is not 0, the error subprocess. CalledProcessError is cited. This object contains the returncode attribute. try... Else T... To check
Subprocess. check_output ()
The parent process waits for the child process to complete.
Returns the output result of the sub-process to the standard output.
Check the exit information. If the returncode is not 0, the error subprocess. CalledProcessError is cited. This object contains the returncode attribute and output attribute. The output attribute is the output result of the standard output. try... Else T... To check.
The usage of these three functions is similar. The following uses subprocess. call () as an example:
Copy codeThe Code is as follows:
>>> Import subprocess
>>> Retcode = subprocess. call (["ls", "-l"])
# The result is the same as that of the command ls-a in shell.
>>> Print retcode
0
Put the program name (ls) and the parameter (-l) together in a table and pass it to subprocess. call ()
Shell is False by default. in Linux, when shell is set to False, popencalls OS .exe cvp () to execute the program specified by args; when shell is set to True, if args is a string, popen directly calls the system Shell to execute the program specified by args. If args is a sequence, the first item of args is to define the program command string, other parameters are additional parameters used to call the system Shell.
The preceding example can also be written as follows:
Copy codeThe Code is as follows: >>> retcode = subprocess. call ("ls-l", shell = True)
In Windows, Popen calls CreateProcess () to execute the external program specified by args regardless of the shell value. If args is a sequence, first use list2line line () to convert it to a string. However, note that not all programs in MS Windows can use list2cmdline to convert it to a command line string.
Subprocess. Popen ()
Copy codeThe Code is as follows:
Class 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)
In fact, the above functions are based on Popen () Encapsulation (wrapper ). These encapsulation aims to make it easy to use sub-processes. When we want to personalize our needs, we need to turn to the Popen class, which generates objects to represent sub-processes.
Unlike the preceding encapsulation, after a Popen object is created, the main program does not automatically wait for the child process to complete. We must call the wait () method of the object before the parent process will wait (that is, block blocking). For example:
Copy codeThe Code is as follows: >>> import subprocess
>>> Child = subprocess. Popen (['ping', '-C', '4', 'blog .linuxeye.com'])
>>> Print 'parent Process'
The running result shows that the parent process does not wait for the completion of child after starting the child process, but runs print directly.
Compare the waiting conditions:
Copy codeThe Code is as follows: >>> import subprocess
>>> Child = subprocess. Popen ('Ping-c4 blog.linuxeye.com ', shell = True)
>>> Child. wait ()
>>> Print 'parent Process'
The running result shows that the parent process runs print after starting the child process and waiting for the completion of the child process.
In addition, you can perform other operations on the child process in the parent process, such as the child object in the above example:
Copy codeThe Code is as follows:
Child. poll () # Check the sub-process status
Child. kill () # Stop the child process
Child. send_signal () # send a signal to the sub-process
Child. terminate () # terminate a child process
The child process PID is stored in child. pid.
Ii. Text Flow Control of sub-Processes
Standard input, standard output, and standard errors of sub-processes are described as follows:
Copy codeThe Code is as follows:
Child. stdin
Child. stdout
Child. stderr
You can change the standard input, standard output, and standard error when creating a sub-process in Popen (), and use subprocess. PIPE connects the input and output of multiple sub-processes to form a pipeline (pipe). The following are two examples:
Copy codeThe Code is as follows: >>> import subprocess
>>> Child1 = subprocess. Popen (["ls", "-l"], stdout = subprocess. PIPE)
>>> Print child1.stdout. read (),
# Or child1.communicate ()
>>> Import subprocess
>>> Child1 = subprocess. Popen (["cat", "/etc/passwd"], stdout = subprocess. PIPE)
>>> Child2 = subprocess. Popen (["grep", "0: 0"], stdin = child1.stdout, stdout = subprocess. PIPE)
>>> Out = child2.communicate ()
Subprocess. PIPE actually provides a cache for text streams. The stdout of child1 outputs the text to the cache, and then the stdin of child2 reads the text from the PIPE. The output text of child2 is also stored in PIPE until the communicate () method reads the text in PIPE from PIPE.
Note: communicate () is a method of the Popen object. This method blocks the parent process until the child process is completed.