and the common wrapper function subprocess

Ever since Python 2.4, Python subprocess module to manage the introduction of child processes to replace some of the old module method: If os.system, os.spawn , os.popen ., Popen2 ., Commands can not only call external command as a child process, and can be connected to the child process input / output / error pipes, access to information relating to return

A, subprocess and the common wrapper function

Run python, we are in a process to create and run. Like Linux, as process, a process can fork a child process, and let the child process exec another program. In Python, we adopted the standard library subprocess package to fork a child process, and to run an external program.
subprocess defined in the package are several function creates the child process, these functions are to create a child process in a different way, so we can choose one to use as needed. In addition subprocess also provides some management standard flow (standard stream) and tools for pipe (pipe), which use text communication between processes.

subprocess.call()

The parent process waits for the child process to complete
return exit information (returncode, the equivalent of Linux exit code)

subprocess.check_call()

The parent process waits for the child process to complete
returns 0
checking exit information, if returncode is not 0, then include error subprocess.CalledProcessError, the object contains returncode property available to check the try ... except ...

subprocess.check_output()

The parent process waits for the child process to complete
returns the output to the standard output of the child process
checks to exit the message, if returncode is not 0, then include error subprocess.CalledProcessError, the object contains returncode attributes and output attributes, attribute output to standard output output As a result, the available try ... except ... to check.

Use of these three functions is similar to the following to subprocess.call () Example:

>>> import subprocess
>>> retcode = subprocess.call(["ls", "-l"])
#和shell中命令ls -a显示结果一样
>>> print retcode
0

The program name (LS) and with parameters that (-l) together subprocess.call passed to a table ()

shell default is False, in Linux, shell = False, the call to the Popen os.execvp () performs the specified program args; shell = True, if args is a string, the Popen Shell directly call system performs the specified program args If args is a sequence, the first term is defined args program command string, the other items are additional parameters when calling system Shell.

The above example can also be written as follows:

>>> retcode = subprocess.call("ls -l",shell=True)

Under Windows, regardless of the value of the shell, Popen call CreateProcess () args specified external program execution. If args is a sequence, the first with list2cmdline () into a string, but note that not all programs can be converted into list2cmdline command-line string under MS Windows.

subprocess.Popen()

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)

Indeed, several of the above functions are based on the Popen () package (wrapper). The purpose of these packages is to let the child process is easy to use. When we want a more personalized needs of our time, we must turn Popen class, which generates objects used to represent the child process.

The above package is different after Popen object is created, the main program does not automatically wait for the child to complete. We have to call the object's wait () method, the parent process will wait (that is blocking block), for example:

>>> import subprocess
>>> child = subprocess.Popen(['ping','-c','4','blog.linuxeye.com'])
>>> print 'parent process'

Seen from the operating results, the parent process and not wait for the completion of the child after the child process open, but run print directly.

Comparison of waiting:

>>> import subprocess
>>> child = subprocess.Popen('ping -c4 blog.linuxeye.com',shell=True)
>>> child.wait()
>>> print 'parent process'

Seen from the operating results, the parent after the child process open and waiting for the completion of the child, and then run print.
In addition, you can also child process the parent process for other operations, such as child objects in our example above:

child.poll() # 检查子进程状态
child.kill() # 终止子进程
child.send_signal() # 向子进程发送信号
child.terminate() # 终止子进程

PID of the child process is stored in child.pid

Second, the text flow control sub-processes

Subprocess standard input, standard output and standard error, respectively, represent the following attributes:

child.stdin
child.stdout
child.stderr

() Can be established when the change in the child process Popen standard input, standard output and standard error, and may be connected together using subprocess.PIPE inputs and outputs of a plurality of sub-processes, constituting the pipe (pipe), the following two examples:

>>> import subprocess
>>> child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
>>> print child1.stdout.read(),
#或者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 provide a buffer zone for the text stream. child1 stdout of the text output to the buffer, then the stdin child2 read from a text of the PIPE away. child2 output text is also stored in the PIPE until Communicate () method to read out the text of the PIPE PIPE from the.
Note: communicate () is a method Popen object, which can clog the parent process until the child process to complete.

Guess you like

Origin www.cnblogs.com/taosiyu/p/12040339.html