1 # subprocess - Subprocesses with accessible I/O streams
3 # For more information about this module, see PEP 324.
5 # Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se>
7 # By obtaining, using, and/or copying this software and/or its
8 # associated documentation, you agree that you have read, understood,
9 # and will comply with the following terms and conditions:
11 # Permission to use, copy, modify, and distribute this software and
12 # its associated documentation for any purpose and without fee is
13 # hereby granted, provided that the above copyright notice appears in
14 # all copies, and that both that copyright notice and this permission
15 # notice appear in supporting documentation, and that the name of the
16 # author not be used in advertising or publicity pertaining to
17 # distribution of the software without specific, written prior
20 # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
22 # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
23 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
24 # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
25 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
26 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
28 # Use of this file within git is permitted under GPLv2.
31 r"""subprocess - Subprocesses with accessible I/O streams
33 This module allows you to spawn processes, connect to their
34 input/output/error pipes, and obtain their return codes. This module
35 intends to replace several other, older modules and functions, like:
43 Information about how the subprocess module can be used to replace these
44 modules and functions can be found below.
48 Using the subprocess module
49 ===========================
50 This module defines one class called Popen:
52 class Popen(args, bufsize=0, executable=None,
53 stdin=None, stdout=None, stderr=None,
54 preexec_fn=None, close_fds=False, shell=False,
55 cwd=None, env=None, universal_newlines=False,
56 startupinfo=None, creationflags=0):
61 args should be a string, or a sequence of program arguments. The
62 program to execute is normally the first item in the args sequence or
63 string, but can be explicitly set by using the executable argument.
65 On UNIX, with shell=False (default): In this case, the Popen class
66 uses os.execvp() to execute the child program. args should normally
67 be a sequence. A string will be treated as a sequence with the string
68 as the only item (the program to execute).
70 On UNIX, with shell=True: If args is a string, it specifies the
71 command string to execute through the shell. If args is a sequence,
72 the first item specifies the command string, and any additional items
73 will be treated as additional shell arguments.
75 On Windows: the Popen class uses CreateProcess() to execute the child
76 program, which operates on strings. If args is a sequence, it will be
77 converted to a string using the list2cmdline method. Please note that
78 not all MS Windows applications interpret the command line the same
79 way: The list2cmdline is designed for applications using the same
80 rules as the MS C runtime.
82 bufsize, if given, has the same meaning as the corresponding argument
83 to the built-in open() function: 0 means unbuffered, 1 means line
84 buffered, any other positive value means use a buffer of
85 (approximately) that size. A negative bufsize means to use the system
86 default, which usually means fully buffered. The default value for
87 bufsize is 0 (unbuffered).
89 stdin, stdout and stderr specify the executed programs' standard
90 input, standard output and standard error file handles, respectively.
91 Valid values are PIPE, an existing file descriptor (a positive
92 integer), an existing file object, and None. PIPE indicates that a
93 new pipe to the child should be created. With None, no redirection
94 will occur; the child's file handles will be inherited from the
95 parent. Additionally, stderr can be STDOUT, which indicates that the
96 stderr data from the applications should be captured into the same
97 file handle as for stdout.
99 If preexec_fn is set to a callable object, this object will be called
100 in the child process just before the child is executed.
102 If close_fds is true, all file descriptors except 0, 1 and 2 will be
103 closed before the child process is executed.
105 if shell is true, the specified command will be executed through the
108 If cwd is not None, the current directory will be changed to cwd
109 before the child is executed.
111 If env is not None, it defines the environment variables for the new
114 If universal_newlines is true, the file objects stdout and stderr are
115 opened as a text files, but lines may be terminated by any of '\n',
116 the Unix end-of-line convention, '\r', the Macintosh convention or
117 '\r\n', the Windows convention. All of these external representations
118 are seen as '\n' by the Python program. Note: This feature is only
119 available if Python is built with universal newline support (the
120 default). Also, the newlines attribute of the file objects stdout,
121 stdin and stderr are not updated by the communicate() method.
123 The startupinfo and creationflags, if given, will be passed to the
124 underlying CreateProcess() function. They can specify things such as
125 appearance of the main window and priority for the new process.
129 This module also defines two shortcut functions:
131 call(*args, **kwargs):
132 Run command with arguments. Wait for command to complete, then
133 return the returncode attribute.
135 The arguments are the same as for the Popen constructor. Example:
137 retcode = call(["ls", "-l"])
142 Exceptions raised in the child process, before the new program has
143 started to execute, will be re-raised in the parent. Additionally,
144 the exception object will have one extra attribute called
145 'child_traceback', which is a string containing traceback information
146 from the childs point of view.
148 The most common exception raised is OSError. This occurs, for
149 example, when trying to execute a non-existent file. Applications
150 should prepare for OSErrors.
152 A ValueError will be raised if Popen is called with invalid arguments.
157 Unlike some other popen functions, this implementation will never call
158 /bin/sh implicitly. This means that all characters, including shell
159 metacharacters, can safely be passed to child processes.
164 Instances of the Popen class have the following methods:
167 Check if child process has terminated. Returns returncode
171 Wait for child process to terminate. Returns returncode attribute.
173 communicate(input=None)
174 Interact with process: Send data to stdin. Read data from stdout
175 and stderr, until end-of-file is reached. Wait for process to
176 terminate. The optional stdin argument should be a string to be
177 sent to the child process, or None, if no data should be sent to
180 communicate() returns a tuple (stdout, stderr).
182 Note: The data read is buffered in memory, so do not use this
183 method if the data size is large or unlimited.
185 The following attributes are also available:
188 If the stdin argument is PIPE, this attribute is a file object
189 that provides input to the child process. Otherwise, it is None.
192 If the stdout argument is PIPE, this attribute is a file object
193 that provides output from the child process. Otherwise, it is
197 If the stderr argument is PIPE, this attribute is file object that
198 provides error output from the child process. Otherwise, it is
202 The process ID of the child process.
205 The child return code. A None value indicates that the process
206 hasn't terminated yet. A negative value -N indicates that the
207 child was terminated by signal N (UNIX only).
210 Replacing older functions with the subprocess module
211 ====================================================
212 In this section, "a ==> b" means that b can be used as a replacement
215 Note: All functions in this section fail (more or less) silently if
216 the executed program cannot be found; this module raises an OSError
219 In the following examples, we assume that the subprocess module is
220 imported with "from subprocess import *".
223 Replacing /bin/sh shell backquote
224 ---------------------------------
227 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
230 Replacing shell pipe line
231 -------------------------
232 output=`dmesg | grep hda`
234 p1 = Popen(["dmesg"], stdout=PIPE)
235 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
236 output = p2.communicate()[0]
239 Replacing os.system()
240 ---------------------
241 sts = os.system("mycmd" + " myarg")
243 p = Popen("mycmd" + " myarg", shell=True)
244 sts = os.waitpid(p.pid, 0)
248 * Calling the program through the shell is usually not required.
250 * It's easier to look at the returncode attribute than the
253 A more real-world example would look like this:
256 retcode = call("mycmd" + " myarg", shell=True)
258 print >>sys.stderr, "Child was terminated by signal", -retcode
260 print >>sys.stderr, "Child returned", retcode
262 print >>sys.stderr, "Execution failed:", e
269 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
271 pid = Popen(["/bin/mycmd", "myarg"]).pid
276 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
278 retcode = call(["/bin/mycmd", "myarg"])
283 os.spawnvp(os.P_NOWAIT, path, args)
285 Popen([path] + args[1:])
290 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
292 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
297 pipe = os.popen(cmd, mode='r', bufsize)
299 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
301 pipe = os.popen(cmd, mode='w', bufsize)
303 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
306 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
308 p = Popen(cmd, shell=True, bufsize=bufsize,
309 stdin=PIPE, stdout=PIPE, close_fds=True)
310 (child_stdin, child_stdout) = (p.stdin, p.stdout)
315 child_stderr) = os.popen3(cmd, mode, bufsize)
317 p = Popen(cmd, shell=True, bufsize=bufsize,
318 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
321 child_stderr) = (p.stdin, p.stdout, p.stderr)
324 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
326 p = Popen(cmd, shell=True, bufsize=bufsize,
327 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
328 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
333 Note: If the cmd argument to popen2 functions is a string, the command
334 is executed through /bin/sh. If it is a list, the command is directly
337 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
339 p = Popen(["somestring"], shell=True, bufsize=bufsize
340 stdin=PIPE, stdout=PIPE, close_fds=True)
341 (child_stdout, child_stdin) = (p.stdout, p.stdin)
344 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
346 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
347 stdin=PIPE, stdout=PIPE, close_fds=True)
348 (child_stdout, child_stdin) = (p.stdout, p.stdin)
350 The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
353 * subprocess.Popen raises an exception if the execution fails
354 * the capturestderr argument is replaced with the stderr argument.
355 * stdin=PIPE and stdout=PIPE must be specified.
356 * popen2 closes all filedescriptors by default, but you have to specify
357 close_fds=True with subprocess.Popen.
363 mswindows = (sys.platform == "win32")
372 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
374 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
375 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
376 from win32api import GetCurrentProcess, DuplicateHandle, \
377 GetModuleFileName, GetVersion
378 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
379 from win32pipe import CreatePipe
380 from win32process import CreateProcess, STARTUPINFO, \
381 GetExitCodeProcess, STARTF_USESTDHANDLES, \
382 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
383 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
385 from _subprocess import *
399 __all__ = ["Popen", "PIPE", "STDOUT", "call"]
402 MAXFD = os.sysconf("SC_OPEN_MAX")
406 # True/False does not exist on 2.2.0
416 for inst in _active[:]:
423 def call(*args, **kwargs):
424 """Run command with arguments. Wait for command to complete, then
425 return the returncode attribute.
427 The arguments are the same as for the Popen constructor. Example:
429 retcode = call(["ls", "-l"])
431 return Popen(*args, **kwargs).wait()
434 def list2cmdline(seq):
436 Translate a sequence of arguments into a command line
437 string, using the same rules as the MS C runtime:
439 1) Arguments are delimited by white space, which is either a
442 2) A string surrounded by double quotation marks is
443 interpreted as a single argument, regardless of white space
444 contained within. A quoted string can be embedded in an
447 3) A double quotation mark preceded by a backslash is
448 interpreted as a literal double quotation mark.
450 4) Backslashes are interpreted literally, unless they
451 immediately precede a double quotation mark.
453 5) If backslashes immediately precede a double quotation mark,
454 every pair of backslashes is interpreted as a literal
455 backslash. If the number of backslashes is odd, the last
456 backslash escapes the next double quotation mark as
461 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
467 # Add a space to separate this argument from the others
471 needquote = (" " in arg) or ("\t" in arg)
477 # Don't know if we need to double yet.
481 result.append('\\' * len(bs_buf)*2)
487 result.extend(bs_buf)
491 # Add remaining backspaces, if any.
493 result.extend(bs_buf)
496 result.extend(bs_buf)
499 return ''.join(result)
503 def __init__(self, args, bufsize=0, executable=None,
504 stdin=None, stdout=None, stderr=None,
505 preexec_fn=None, close_fds=False, shell=False,
506 cwd=None, env=None, universal_newlines=False,
507 startupinfo=None, creationflags=0):
508 """Create new Popen instance."""
511 if not isinstance(bufsize, (int, long)):
512 raise TypeError("bufsize must be an integer")
515 if preexec_fn is not None:
516 raise ValueError("preexec_fn is not supported on Windows "
519 raise ValueError("close_fds is not supported on Windows "
523 if startupinfo is not None:
524 raise ValueError("startupinfo is only supported on Windows "
526 if creationflags != 0:
527 raise ValueError("creationflags is only supported on Windows "
534 self.returncode = None
535 self.universal_newlines = universal_newlines
537 # Input and output objects. The general principle is like
542 # p2cwrite ---stdin---> p2cread
543 # c2pread <--stdout--- c2pwrite
544 # errread <--stderr--- errwrite
546 # On POSIX, the child objects are file descriptors. On
547 # Windows, these are Windows file handles. The parent objects
548 # are file descriptors on both platforms. The parent objects
549 # are None when not using PIPEs. The child objects are None
550 # when not redirecting.
554 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
556 self._execute_child(args, executable, preexec_fn, close_fds,
557 cwd, env, universal_newlines,
558 startupinfo, creationflags, shell,
564 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
566 if universal_newlines:
567 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
569 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
571 if universal_newlines:
572 self.stderr = os.fdopen(errread, 'rU', bufsize)
574 self.stderr = os.fdopen(errread, 'rb', bufsize)
579 def _translate_newlines(self, data):
580 data = data.replace("\r\n", "\n")
581 data = data.replace("\r", "\n")
589 def _get_handles(self, stdin, stdout, stderr):
590 """Construct and return tupel with IO objects:
591 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
593 if stdin == None and stdout == None and stderr == None:
594 return (None, None, None, None, None, None)
596 p2cread, p2cwrite = None, None
597 c2pread, c2pwrite = None, None
598 errread, errwrite = None, None
601 p2cread = GetStdHandle(STD_INPUT_HANDLE)
603 p2cread, p2cwrite = CreatePipe(None, 0)
604 # Detach and turn into fd
605 p2cwrite = p2cwrite.Detach()
606 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
607 elif type(stdin) == types.IntType:
608 p2cread = msvcrt.get_osfhandle(stdin)
610 # Assuming file-like object
611 p2cread = msvcrt.get_osfhandle(stdin.fileno())
612 p2cread = self._make_inheritable(p2cread)
615 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
617 c2pread, c2pwrite = CreatePipe(None, 0)
618 # Detach and turn into fd
619 c2pread = c2pread.Detach()
620 c2pread = msvcrt.open_osfhandle(c2pread, 0)
621 elif type(stdout) == types.IntType:
622 c2pwrite = msvcrt.get_osfhandle(stdout)
624 # Assuming file-like object
625 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
626 c2pwrite = self._make_inheritable(c2pwrite)
629 errwrite = GetStdHandle(STD_ERROR_HANDLE)
631 errread, errwrite = CreatePipe(None, 0)
632 # Detach and turn into fd
633 errread = errread.Detach()
634 errread = msvcrt.open_osfhandle(errread, 0)
635 elif stderr == STDOUT:
637 elif type(stderr) == types.IntType:
638 errwrite = msvcrt.get_osfhandle(stderr)
640 # Assuming file-like object
641 errwrite = msvcrt.get_osfhandle(stderr.fileno())
642 errwrite = self._make_inheritable(errwrite)
644 return (p2cread, p2cwrite,
649 def _make_inheritable(self, handle):
650 """Return a duplicate of handle, which is inheritable"""
651 return DuplicateHandle(GetCurrentProcess(), handle,
652 GetCurrentProcess(), 0, 1,
653 DUPLICATE_SAME_ACCESS)
656 def _find_w9xpopen(self):
657 """Find and return absolut path to w9xpopen.exe"""
658 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
660 if not os.path.exists(w9xpopen):
661 # Eeek - file-not-found - possibly an embedding
662 # situation - see if we can locate it in sys.exec_prefix
663 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
665 if not os.path.exists(w9xpopen):
666 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
667 "needed for Popen to work with your "
668 "shell or platform.")
672 def _execute_child(self, args, executable, preexec_fn, close_fds,
673 cwd, env, universal_newlines,
674 startupinfo, creationflags, shell,
678 """Execute program (MS Windows version)"""
680 if not isinstance(args, types.StringTypes):
681 args = list2cmdline(args)
683 # Process startup details
684 default_startupinfo = STARTUPINFO()
685 if startupinfo == None:
686 startupinfo = default_startupinfo
687 if not None in (p2cread, c2pwrite, errwrite):
688 startupinfo.dwFlags |= STARTF_USESTDHANDLES
689 startupinfo.hStdInput = p2cread
690 startupinfo.hStdOutput = c2pwrite
691 startupinfo.hStdError = errwrite
694 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
695 default_startupinfo.wShowWindow = SW_HIDE
696 comspec = os.environ.get("COMSPEC", "cmd.exe")
697 args = comspec + " /c " + args
698 if (GetVersion() >= 0x80000000L or
699 os.path.basename(comspec).lower() == "command.com"):
700 # Win9x, or using command.com on NT. We need to
701 # use the w9xpopen intermediate program. For more
702 # information, see KB Q150956
703 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
704 w9xpopen = self._find_w9xpopen()
705 args = '"%s" %s' % (w9xpopen, args)
706 # Not passing CREATE_NEW_CONSOLE has been known to
707 # cause random failures on win9x. Specifically a
708 # dialog: "Your program accessed mem currently in
709 # use at xxx" and a hopeful warning about the
710 # stability of your system. Cost is Ctrl+C wont
712 creationflags |= CREATE_NEW_CONSOLE
716 hp, ht, pid, tid = CreateProcess(executable, args,
717 # no special security
719 # must inherit handles to pass std
726 except pywintypes.error, e:
727 # Translate pywintypes.error to WindowsError, which is
728 # a subclass of OSError. FIXME: We should really
729 # translate errno using _sys_errlist (or simliar), but
730 # how can this be done from Python?
731 raise WindowsError(*e.args)
733 # Retain the process handle, but close the thread handle
738 # Child is launched. Close the parent's copy of those pipe
739 # handles that only the child should have open. You need
740 # to make sure that no handles to the write end of the
741 # output pipe are maintained in this process or else the
742 # pipe will not close when the child process exits and the
743 # ReadFile will hang.
753 """Check if child process has terminated. Returns returncode
755 if self.returncode == None:
756 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
757 self.returncode = GetExitCodeProcess(self._handle)
759 return self.returncode
763 """Wait for child process to terminate. Returns returncode
765 if self.returncode == None:
766 obj = WaitForSingleObject(self._handle, INFINITE)
767 self.returncode = GetExitCodeProcess(self._handle)
769 return self.returncode
772 def _readerthread(self, fh, buffer):
773 buffer.append(fh.read())
776 def communicate(self, input=None):
777 """Interact with process: Send data to stdin. Read data from
778 stdout and stderr, until end-of-file is reached. Wait for
779 process to terminate. The optional input argument should be a
780 string to be sent to the child process, or None, if no data
781 should be sent to the child.
783 communicate() returns a tuple (stdout, stderr)."""
784 stdout = None # Return
785 stderr = None # Return
789 stdout_thread = threading.Thread(target=self._readerthread,
790 args=(self.stdout, stdout))
791 stdout_thread.setDaemon(True)
792 stdout_thread.start()
795 stderr_thread = threading.Thread(target=self._readerthread,
796 args=(self.stderr, stderr))
797 stderr_thread.setDaemon(True)
798 stderr_thread.start()
802 self.stdin.write(input)
810 # All data exchanged. Translate lists into strings.
816 # Translate newlines, if requested. We cannot let the file
817 # object do the translation: It is based on stdio, which is
818 # impossible to combine with select (unless forcing no
820 if self.universal_newlines and hasattr(open, 'newlines'):
822 stdout = self._translate_newlines(stdout)
824 stderr = self._translate_newlines(stderr)
827 return (stdout, stderr)
833 def _get_handles(self, stdin, stdout, stderr):
834 """Construct and return tupel with IO objects:
835 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
837 p2cread, p2cwrite = None, None
838 c2pread, c2pwrite = None, None
839 errread, errwrite = None, None
844 p2cread, p2cwrite = os.pipe()
845 elif type(stdin) == types.IntType:
848 # Assuming file-like object
849 p2cread = stdin.fileno()
854 c2pread, c2pwrite = os.pipe()
855 elif type(stdout) == types.IntType:
858 # Assuming file-like object
859 c2pwrite = stdout.fileno()
864 errread, errwrite = os.pipe()
865 elif stderr == STDOUT:
867 elif type(stderr) == types.IntType:
870 # Assuming file-like object
871 errwrite = stderr.fileno()
873 return (p2cread, p2cwrite,
878 def _set_cloexec_flag(self, fd):
880 cloexec_flag = fcntl.FD_CLOEXEC
881 except AttributeError:
884 old = fcntl.fcntl(fd, fcntl.F_GETFD)
885 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
888 def _close_fds(self, but):
889 for i in range(3, MAXFD):
898 def _execute_child(self, args, executable, preexec_fn, close_fds,
899 cwd, env, universal_newlines,
900 startupinfo, creationflags, shell,
904 """Execute program (POSIX version)"""
906 if isinstance(args, types.StringTypes):
910 args = ["/bin/sh", "-c"] + args
912 if executable == None:
915 # For transferring possible exec failure from child to parent
916 # The first char specifies the exception type: 0 means
917 # OSError, 1 means some other error.
918 errpipe_read, errpipe_write = os.pipe()
919 self._set_cloexec_flag(errpipe_write)
925 # Close parent's pipe ends
932 os.close(errpipe_read)
942 # Close pipe fds. Make sure we doesn't close the same
946 if c2pwrite and c2pwrite not in (p2cread,):
948 if errwrite and errwrite not in (p2cread, c2pwrite):
951 # Close all other fds, if asked for
953 self._close_fds(but=errpipe_write)
962 os.execvp(executable, args)
964 os.execvpe(executable, args, env)
967 exc_type, exc_value, tb = sys.exc_info()
968 # Save the traceback and attach it to the exception object
969 exc_lines = traceback.format_exception(exc_type,
972 exc_value.child_traceback = ''.join(exc_lines)
973 os.write(errpipe_write, pickle.dumps(exc_value))
975 # This exitcode won't be reported to applications, so it
976 # really doesn't matter what we return.
980 os.close(errpipe_write)
981 if p2cread and p2cwrite:
983 if c2pwrite and c2pread:
985 if errwrite and errread:
988 # Wait for exec to fail or succeed; possibly raising exception
989 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
990 os.close(errpipe_read)
992 os.waitpid(self.pid, 0)
993 child_exception = pickle.loads(data)
994 raise child_exception
997 def _handle_exitstatus(self, sts):
998 if os.WIFSIGNALED(sts):
999 self.returncode = -os.WTERMSIG(sts)
1000 elif os.WIFEXITED(sts):
1001 self.returncode = os.WEXITSTATUS(sts)
1003 # Should never happen
1004 raise RuntimeError("Unknown child exit status!")
1006 _active.remove(self)
1010 """Check if child process has terminated. Returns returncode
1012 if self.returncode == None:
1014 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1016 self._handle_exitstatus(sts)
1019 return self.returncode
1023 """Wait for child process to terminate. Returns returncode
1025 if self.returncode == None:
1026 pid, sts = os.waitpid(self.pid, 0)
1027 self._handle_exitstatus(sts)
1028 return self.returncode
1031 def communicate(self, input=None):
1032 """Interact with process: Send data to stdin. Read data from
1033 stdout and stderr, until end-of-file is reached. Wait for
1034 process to terminate. The optional input argument should be a
1035 string to be sent to the child process, or None, if no data
1036 should be sent to the child.
1038 communicate() returns a tuple (stdout, stderr)."""
1041 stdout = None # Return
1042 stderr = None # Return
1045 # Flush stdio buffer. This might block, if the user has
1046 # been writing to .stdin in an uncontrolled fashion.
1049 write_set.append(self.stdin)
1053 read_set.append(self.stdout)
1056 read_set.append(self.stderr)
1059 while read_set or write_set:
1060 rlist, wlist, xlist = select.select(read_set, write_set, [])
1062 if self.stdin in wlist:
1063 # When select has indicated that the file is writable,
1064 # we can write up to PIPE_BUF bytes without risk
1065 # blocking. POSIX defines PIPE_BUF >= 512
1066 bytes_written = os.write(self.stdin.fileno(), input[:512])
1067 input = input[bytes_written:]
1070 write_set.remove(self.stdin)
1072 if self.stdout in rlist:
1073 data = os.read(self.stdout.fileno(), 1024)
1076 read_set.remove(self.stdout)
1079 if self.stderr in rlist:
1080 data = os.read(self.stderr.fileno(), 1024)
1083 read_set.remove(self.stderr)
1086 # All data exchanged. Translate lists into strings.
1088 stdout = ''.join(stdout)
1090 stderr = ''.join(stderr)
1092 # Translate newlines, if requested. We cannot let the file
1093 # object do the translation: It is based on stdio, which is
1094 # impossible to combine with select (unless forcing no
1096 if self.universal_newlines and hasattr(open, 'newlines'):
1098 stdout = self._translate_newlines(stdout)
1100 stderr = self._translate_newlines(stderr)
1103 return (stdout, stderr)
1108 # Example 1: Simple redirection: Get process list
1110 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1111 print "Process list:"
1115 # Example 2: Change uid before executing child
1117 if os.getuid() == 0:
1118 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1122 # Example 3: Connecting several subprocesses
1124 print "Looking for 'hda'..."
1125 p1 = Popen(["dmesg"], stdout=PIPE)
1126 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1127 print repr(p2.communicate()[0])
1130 # Example 4: Catch execution error
1133 print "Trying a weird file..."
1135 print Popen(["/this/path/does/not/exist"]).communicate()
1137 if e.errno == errno.ENOENT:
1138 print "The file didn't exist. I thought so..."
1139 print "Child traceback:"
1140 print e.child_traceback
1142 print "Error", e.errno
1144 print >>sys.stderr, "Gosh. No error."
1147 def _demo_windows():
1149 # Example 1: Connecting several subprocesses
1151 print "Looking for 'PROMPT' in set output..."
1152 p1 = Popen("set", stdout=PIPE, shell=True)
1153 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1154 print repr(p2.communicate()[0])
1157 # Example 2: Simple execution of program
1159 print "Executing calc..."
1164 if __name__ == "__main__":