Content-Type: text/x-zim-wiki Wiki-Format: zim 0.4 Creation-Date: 2012-01-05T16:23:46+08:00 ====== subprocess ====== Created Thursday 05 January 2012 ===== 17.1. subprocess — Subprocess management ===== New in version 2.4. The subprocess module allows you to__ spawn__ new processes, connect to their__ input/output/error pipes__, and obtain their __return codes__. This module intends to **replace** several other, older modules and functions, such as: * os.system * os.spawn* * os.popen* * popen2.* * commands.* subprocess是推荐的执行shell命令或子进程的方式。 Information about how the subprocess module can be used to replace these modules and functions can be found in the following sections. See also: PEP 324 – PEP proposing the subprocess module ===== 17.1.1. Using the subprocess Module ===== The recommended approach to invoking subprocesses is to use the following convenience functions for all use cases they can handle. For more advanced use cases, the underlying __Popen__ interface can be used directly. 三个模块函数: * subprocess.__call__(**args**, *, stdin=None, stdout=None, stderr=None, shell=False) * subprocess.__check_call__(args, *, stdin=None, stdout=None, stderr=None, shell=False) * subprocess.__check_output__(args, *, stdin=None, stderr=None, shell=False, **universal_newlines**=False) 两个模块变量: __subprocess.PIPE__ __subprocess.STDOUT__ 在功能能满足的情况下,尽量使用上面的三个函数,更复杂的交互式控制可以使用subprocess中提供的__Popen()类__。前两个函数返回命令的退出码,最后一个命令返回命令的输出为字符串。 [*] subprocess.__call__(**args**, *, stdin=None, stdout=None, stderr=None, shell=False) Run the command described by __args__. __Wait __for command to complete, then return the **returncode** attribute. 适合非交互式进程,执行args指定的程序直到其结束,返回退出码,即使命令执行失败,也不产生异常。stdin,stdout,stderr一般不使用PIPE,因为调用进程一般不读这种非交互式进程的输出。stdin为None表示子进程的stdin将__继承__调用进程的描述符。 The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the __Popen__ constructor - this functions passes all supplied arguments directly through to that interface. Examples: >>> __#如果shell=False(默认),则python调用os.exelp()来执行args,因此,如果args是字符串,则只能包含命令名;如果是序列,则可以包含命令参数(参数不支持shell的特性如文件名扩展等。)。__ >>> subprocess.call(__["ls", "-l"]__) 0 __#如果shell=True,则python调用system shell来执行args,调用形式为: execlp("/bin/sh", '-c', 'arg1', 'arg2', ....)因此,如果args是字符串,则其中可以包含命令参数,而且支持各种shell特性如文件名扩展、命令扩展等;如果args是序列,则其第一个元素为命令名,其它元素为被当作shell本身的参数。__ >>> subprocess.call("exit 1", shell=True) 1 __总的来说__**:**如果shell=False, python使用os.execvp(...)来执行args,因此,如果args是一个string,则该string__只能是__命令名称, 如果要为命令附加参数,则只能使用序列类型; 如果shell=True,则python使用shell来执行行args,因此,args最好是一个string,该string可以包含命令名及其参数,如果使用序列,则从第二个元素开始作为shell本身的参数(而非命令的参数。)。 Invoking the system shell with shell=True can be **a security hazard** if combined with untrusted input. See the warning under Frequently Used Arguments for details. __Do not use stdout=PIPE or stderr=PIPE with this function__. As the pipes are not being read in the current process, the child process may block if it generates enough output to a pipe to fill up the OS pipe buffer. 当使用stdout=PIPE时,如果子进程填满了管道而调用进程没有读该管道时__子进程就会被阻塞__。因此使用上面三个函数时一般不使用这个参数。 The standard input and output channels for the process started by call() are__ bound to the parent’s input and output__. That means the calling programm __cannot capture the output__ of the command. Use check_output() to capture the output for later processing. [*] subprocess.**check_call**(args, *, stdin=None, stdout=None, stderr=None, shell=False) 和call类似,但是对返回值进行检查,如果非0则引发异常。 Run command with arguments. Wait for command to complete. **If the return code was zero then return**, otherwise raise__ CalledProcessError__. The CalledProcessError object will have the **return code **in the **returncode** attribute. T Examples: >>> >>> subprocess.check_call(["ls", "-l"]) 0 >>> subprocess.check_call("exit 1", shell=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 Note Do not use stdout=PIPE or stderr=PIPE with this function. As the pipes are not being read in the current process, the child process may block if it generates enough output to a pipe to fill up the OS pipe buffer. [*] subprocess.__check_output__(args, *, stdin=None, stderr=None, shell=False, **universal_newlines**=False) 执行命令,返回命令的输出为一字符串。如果命令执行失败,则产生异常。 Run command with arguments and return its output as a__ byte string__. If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. Examples: >>> >>> subprocess.check_output(["echo", "Hello World!"]) 'Hello World!\n' >>> subprocess.check_output("exit 1", shell=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 To also capture standard error in the result, use__ stderr=subprocess.STDOUT__: >>> >>> subprocess.check_output( ... "ls non_existent_file; exit 0", ... stderr=subprocess.STDOUT, ... shell=True) 'ls: non_existent_file: No such file or directory\n' Note Do not use stderr=PIPE with this function. As the pipe is not being read in the current process, the child process may block if it generates enough output to the pipe to fill up the OS pipe buffer. __subprocess.PIPE__ Special value that can be used as the** stdin, stdout or stderr** argument to Popen and indicates that a pipe to the standard stream should be opened. 如果stdin=PIPE, 则Popen(...)返回的Popen型对象的stdin属性返回一__写打开的文件对象__,向此文件写入的内容将会被传给子进程。stdout, stderr类似。 __subprocess.STDOUT__ Special value that can be used as the **stderr** argument to Popen and indicates that standard error should go into the same handle as standard output. 表示子进程的stderr被重定向**其stdout对应的文件中**。 === 17.1.1.1. Frequently Used Arguments === To support a wide variety of use cases, the __Popen constructor__ (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are: * args is required for all calls and should be **a **__string__**, or a **__sequence__** of program arguments**. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either __shell must be True__ (see below) or else the string must simply name the program to be executed __without__ specifying any arguments. 使用序列形式是首选的方式,这时一般将shell=False,python直接调用os.execlp()。这样可以避免shell代码注入风险。 * stdin, stdout and stderr specify the __executed program’s __standard input, standard output and standard error **file handles**, respectively. Valid values are__ PIPE, an existing file descriptor (a positive integer), an existing file object, and None__. PIPE indicates that a new pipe to the child should be created. With the default settings of None, no** redirection** will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into **the same file** handle as for stdout. When stdout or stderr are pipes and universal_newlines is True then all line endings will be converted to__ '\n'__ as described for the universal newlines ‘U’` mode argument to open(). * If shell is True, the specified command will be** executed through the shell**. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want __access to other shell features__ such as **filename wildcards, shell pipes and environment variable expansion**. 使用shell时,args的字符串形式是首选的方式。 Warning Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of __shell=True is strongly discouraged__ in cases where the command string is constructed from external input: >>> >>> from subprocess import call >>> filename = input("What file would you like to display?\n") What file would you like to display? non_existent; rm -rf / # >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly... shell=False disables all shell based features, but does not suffer from this vulnerability; see the Note in the Popen constructor documentation for helpful hints in getting shell=False to work. These options, along with all of the other options, are described in more detail in the Popen constructor documentation. ==== 17.1.1.2. Popen Constructor ==== subprocess模块中只定义了一个类:Popen The **underlying** process creation and management in this module is handled by the__ Popen__ class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions. __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) Arguments are: * args should be a string, or a sequence of program arguments. The program to execute is normally the **first item** in the args sequence or the string(string作为命令名,不能有参数) if a string is given, but can be **explicitly set **by using the __executable__ argument. When executable is given, the first item in the args sequence is still treated by most programs as the** command name**, which can then be different from the actual executable name. On Unix, it becomes the** display name** for the executing program in utilities such as ps. 如果ecutable被设置,则其值将作为__实际执行__的命令名。args的第一个元素将作为命令的显示名称。 On Unix, with shell=False (default): In this case, the __Popen class uses os.execvp()__ to execute the child program. args should **normally be a sequence.** If a string is specified for args, it will be used as the **name or path of the program **to execute; this will only work if the program is being given __no__ arguments. 默认情况下shell=False,这样args通常为sequence,其第一个元素为待执行的命令,其它元素为命令参数。如果args为string,则其**只能为命令名或命令路径,不能带任何参数**。这时因为python使用os.execvp()来执行这个string。 Note __shlex.split()__ can be useful when determining the correct tokenization for args, especially in complex cases: >>> >>> import shlex, subprocess >>> command_line = raw_input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print args ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in **separate list elements**, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. On Unix, with shell=True: __If args is a string, it specifies the command string to execute through the shell.__ This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments __to the shell itself__. That is to say, Popen does the equivalent of: 在shell=True的情况下,args**最好是一个字符串**。如果是序列,则从第二个元素开始是__作为shell本身的参数__,而非命令的参数。 __ Popen(['/bin/sh', '-c', args[0], args[1], ...])__ On Windows: the Popen class uses CreateProcess() to execute the child child program, which __operates on strings.__ If args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. **总的来说:如果shell=False, python使用os.execvp(...)来执行args,因此,如果args是一个string,则该string只能是命令名称, 如果要为命令执行参数,则只能使用序列类型; 如果shell=True,则python使用shell来执行行args,因此,args最好是一个string,该string可以包含命令名及其参数,如果使用序列,则从第二个元素开始作为**__shell本身__**的参数(而非命令的参数。)。** * bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: **0 means **__unbuffered__**, 1 means**__ line buffered__**, any other positive value means use a buffer of (approximately) that size**. A negative bufsize means to use the system **default**, which usually means__ fully__ buffered. The** default value for bufsize is 0** __(unbuffered)__. 控制打开文件的缓冲方式,默认为unbuffered。 Note If you experience performance issues, it is recommended that you try to enable buffering by setting bufsize to either -1 or a large enough positive value (such as 4096). * The executable argument **specifies the program** to execute. It is very seldom needed: Usually, the program to execute is defined by the **args** argument. If shell=True, the executable argument specifies __which shell to use__. On Unix, the default shell is **/bin/sh**. On Windows, the default shell is specified by the COMSPEC environment variable. The only reason you would need to specify shell=True on Windows is where the command you wish to execute is actually built in to the shell, eg dir, copy. You don’t need shell=True to run a batch file, nor to run a console-based executable. * stdin, stdout and stderr specify the __executed program’s __standard input, standard output and standard error file handles, respectively. Valid values are __PIPE, an existing file descriptor (a positive integer), an existing file object, and None__. PIPE indicates that a new pipe to the child should be created. With the **default settings of None**, no redirection will occur; the child’s file handles will be **inherited from the parent**. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout. * If__ preexec_fn__ is set to a callable object, this object will be called in the child process just **before** the child is executed. (Unix only) * If close_fds is true,__ all file descriptors except 0, 1 and 2 will be closed__ before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr. * If shell is True, the specified command will be executed through the shell. Warning Enabling this option can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details. * If cwd is not None, the child’s current directory will be changed to cwd **before **it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd. * If env is not None, it must be __a mapping__ that defines the environment variables for the new process; these are used instead of** inheriting** the current process’ environment, which is the default behavior. Note If specified, __env must provide any variables__ required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid SystemRoot. * If universal_newlines is True, the file objects stdout and stderr are __opened as text files__, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the old Macintosh convention or '\r\n', the Windows convention. All of these external representations are __seen as '\n' __by the Python program. Note This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. * If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying __CreateProcess __function. * creationflags, if given, can be CREATE_NEW_CONSOLE or CREATE_NEW_PROCESS_GROUP. (Windows only)? ==== 17.1.1.3. Exceptions ==== Exceptions raised in the child process, before the new program has started to execute, will be__ re-raised in the parent__. Additionally, the exception object will have one extra attribute called **child_traceback**, which is a string containing traceback information from the child’s point of view. The most common exception raised is __OSError__. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions. A __ValueError __will be raised if Popen is called with invalid arguments. check_call() and check_output() will raise__ CalledProcessError__ if the called process returns a** non-zero** return code. ==== 17.1.1.4. Security ==== 最好不要使用shell=True参数。 Unlike some other popen functions, this implementation will **never call a system shell implicitly**. This means that all characters, including shell metacharacters, can __safely__ be passed to child processes. Obviously, if the shell is invoked explicitly, then it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately. ==== 17.1.2. Popen Objects ==== Popen()函数返回一个__Popen对象__。 Instances of the Popen class have the following methods: **Popen.poll()** Check if child process __has terminated__. Set and return **returncode** attribute. **Popen.wait()** Wait for child process to terminate. Set and return **returncode** attribute. Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. __Popen.communicate__(input=None) Interact with process: **Send data to stdin**. Read data from stdout and stderr, until __end-of-file__ is reached. Wait for process to terminate. The optional input argument should be __a string to be sent to the child process__, or None, if no data should be sent to the child. communicate() returns __a tuple__ (stdoutdata, stderrdata). Note that if you want to send data to the process’s stdin, you need to create the Popen object with__ stdin=PIPE__. Similarly, to get anything other than None in the result tuple, you need to give__ stdout=PIPE__ and/or __stderr=PIPE__ too. Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited. **Popen.send_signal(signal)** Sends the signal signal to the child. Note On Windows, **SIGTERM **is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP. **Popen.terminate()** Stop the child. On Posix OSs the method sends __SIGTERM__ to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child. **Popen.kill()** Kills the child. On Posix OSs the function sends __SIGKILL__ to the child. On Windows kill() is an alias for terminate(). ===== The following attributes are also available: ===== **Popen对象**具有下列属性: Warning Use communicate() rather than //.stdin.write, .stdout.read or .stderr.read// to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Popen.stdin #对Popen调用stdin属性,将返回一个**写打开的文件对象**。 If the stdin argument was PIPE, this attribute is **a file object** that provides input to the child process. Otherwise, it is__ None__. Popen.stdout If the stdout argument was PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. Popen.stderr If the stderr argument was PIPE, this attribute is a file object that provides error output from the child process. Otherwise, it is None. Popen.__pid__ The process ID of the child process. Note that if you set the shell argument to True, this is the process ID of the __spawned shell__. Popen.__returncode__ The child return code, **set by poll() and wait()** (and indirectly by communicate()). A __None__ value indicates that the process hasn’t terminated yet. A negative value __-N__ indicates that the child was **terminated by signal N** (Unix only). ===== 17.1.3.1. Constants ===== The subprocess module exposes the following constants. subprocess.STD_INPUT_HANDLE The __standard input device__. Initially, this is the console input buffer, CONIN$. subprocess.STD_OUTPUT_HANDLE The standard output device. Initially, this is the active console screen buffer, CONOUT$. subprocess.STD_ERROR_HANDLE The standard error device. Initially, this is the active console screen buffer, CONOUT$. subprocess.SW_HIDE Hides the window. Another window will be activated. subprocess.STARTF_USESTDHANDLES Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain additional information. subprocess.STARTF_USESHOWWINDOW Specifies that the STARTUPINFO.wShowWindow attribute contains additional information. subprocess.CREATE_NEW_CONSOLE The new process ha**s a new console**, instead of inheriting its parent’s console __(the default)__. This flag is always set when Popen is created with shell=True. subprocess.CREATE_NEW_PROCESS_GROUP A Popen creationflags parameter to specify that __a new process group__ will be created. This flag is necessary for using __os.kill()__ on the subprocess. This flag is ignored if CREATE_NEW_CONSOLE is specified. ==== 17.1.4. Replacing Older Functions with the subprocess Module ==== In this section, “a becomes b” means that b can be used as a replacement for a. Note All “a” functions in this section** fail (more or less) silently** if the executed program cannot be found; the “b” replacements raise__ OSError__ instead. In addition, the replacements using check_output() will fail with a __CalledProcessError__ if the requested operation produces a **non-zero** return code. The output is still available as the output attribute of the raised exception. 如果子进程返回非0值,check_output将引发异常。 In the following examples, we assume that the relevant functions have already been imported from the subprocess module. === 17.1.4.1. Replacing /bin/sh shell backquote === output=`mycmd myarg` # becomes **output **= __check_output__(["mycmd", "myarg"]) === 17.1.4.2. Replacing shell pipeline === output=`dmesg | grep hda` # becomes p1 = Popen(["dmesg"], __stdout=PIPE__) p2 = Popen(["grep", "hda"], stdin=__p1.stdout__, stdout=PIPE) #p1是Popen对象,其stdout返回一个读打开的文件对象(因为p1的stdout为PIPE)。 __p1.stdout__.close() # Allow p1 to receive a SIGPIPE if p2 exits,**关键!!!** output = __p2.communicate()__[0] #communicate()返回一个__元组__,这里只取出第一个元素即子进程的标准输出。 The p1.stdout.close() call after starting the p2 is __important in order__ for p1 to receive a SIGPIPE if p2 exits before p1. 具体解释如下:stackoverflow.com/q/7391689 From Wikipedia, SIGPIPE is the signal sent to a process when it attempts to **write** to a pipe without a process connected to the other end. When you first create p1 using **stdout=PIPE**, there is one process connected to the pipe, which is __your Python process__, and you can read the output using p1.stdout. 最开始Popen()时,python解释器会连接到p1.stdout管道,这样在p2没有创建前,p1的cmd就可以执行了,输出将临时地放入管道中。 When you create p2 using stdin=p1.stdout there are now __two processes__ connected to the pipe p1.stdout. Generally when you are running processes in a pipeline you want **all processes** to end when any of the processes end. For this to happen automatically __you need to close p1.stdout so p2.stdin is the only process attached to that pipe__, this way if p2 ends and p1 writes additional data to stdout, it will receive a SIGPIPE since there are no longer any processes attached to that pipe. Alternatively, for **trusted input**, the shell’s own pipeline support may still be used directly: output=`dmesg | grep hda` # becomes output=__check_output__(“dmesg | grep hda”,__ shell=True__) ==== 17.1.4.3. Replacing os.system() ==== sts = os.system("mycmd" + " myarg") #os.system是**调用一个shell**来执行其参数对应的命令,返回的是子进程的退出值。 # becomes sts =__ call__("mycmd" + " myarg",__ shell=True__) #返回子进程的退出值,即使为非0值时不会引发异常。 Notes: Calling the program through the shell is usually not required. A more realistic example would look like this: try: **retcode** = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", __-retcode__ else: print >>sys.stderr, "Child returned", retcode __except OSError, e:__ print **>>sys.stderr**, "Execution failed:", e ==== 17.1.4.4. Replacing the os.spawn family ==== P_NOWAIT example: __pid__ = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).__pid__ P_WAIT example: __retcode__ = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], **env**={"PATH": "/usr/bin"}) ==== 17.1.4.5. Replacing os.popen(), os.popen2(), os.popen3() ==== pipe = os.popen("cmd", __'r'__, bufsize) #第二个参数指定管道打开的方式。 ==> pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE)__.stdout__ pipe = os.popen("cmd", 'w', bufsize) ==> pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE)__.stdin__ (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize) #popen2同时返回与子进程相连的读、写__管道描述符__。 ==> p = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) #返回与子进程相连的读、写__文件对象__。 (child_stdin, child_stdout, child_stderr) = os.popen3("cmd", mode, bufsize) ==> p = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, **stderr=PIPE**, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode, bufsize) ==> p = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, __stderr=STDOUT__, close_fds=True) #STDOUT标示,子进程的标准出错和__它的__标准输出__重定向到同一个__文件。 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) On Unix, os.popen2, os.popen3 and os.popen4 also accept __a sequence__ as the command to execute, in which case arguments will be passed **directly to the program** without shell intervention. This usage can be replaced as follows: (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode, bufsize) ==> p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE) (child_stdin, child_stdout) = (p.stdin, p.stdout) Return code handling translates as follows: pipe = os.popen("cmd", 'w') ... rc = pipe.close() //"cmd"进程读管道时收到EOF,程序一般将终止。 if rc is not None and rc **>> 8**: print "There were some errors" ==> process = Popen("cmd", 'w', shell=True, stdin=PIPE) ... process.stdin.close() //**同样使'cmd'读到EOF**,而自动终止。 if **process.wait()** != 0: print "There were some errors" ==== 17.1.4.6. Replacing functions from the popen2 module ==== (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to the program without shell intervention. This usage can be replaced as follows: (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that: * Popen raises an exception if the execution fails. * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen. ===== 17.1.5. Notes ===== 17.1.5.1. Converting an argument sequence to a string on Windows On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime): * Arguments are delimited by white space, which is either a space or a tab. * A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. * A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. * Backslashes are interpreted literally, unless they immediately precede a double quotation mark. * If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.