12 r"""subprocess - Subprocesses with accessible I/O streams
14 This module allows you to spawn processes, connect to their
15 input/output/error pipes, and obtain their return codes. This module
16 intends to replace several other, older modules and functions, like:
24 Information about how the subprocess module can be used to replace these
25 modules and functions can be found below.
29 Using the subprocess module
30 ===========================
31 This module defines one class called Popen:
33 class Popen(args, bufsize=0, executable=None,
34 stdin=None, stdout=None, stderr=None,
35 preexec_fn=None, close_fds=False, shell=False,
36 cwd=None, env=None, universal_newlines=False,
37 startupinfo=None, creationflags=0):
42 args should be a string, or a sequence of program arguments. The
43 program to execute is normally the first item in the args sequence or
44 string, but can be explicitly set by using the executable argument.
46 On UNIX, with shell=False (default): In this case, the Popen class
47 uses os.execvp() to execute the child program. args should normally
48 be a sequence. A string will be treated as a sequence with the string
49 as the only item (the program to execute).
51 On UNIX, with shell=True: If args is a string, it specifies the
52 command string to execute through the shell. If args is a sequence,
53 the first item specifies the command string, and any additional items
54 will be treated as additional shell arguments.
56 On Windows: the Popen class uses CreateProcess() to execute the child
57 program, which operates on strings. If args is a sequence, it will be
58 converted to a string using the list2cmdline method. Please note that
59 not all MS Windows applications interpret the command line the same
60 way: The list2cmdline is designed for applications using the same
61 rules as the MS C runtime.
63 bufsize, if given, has the same meaning as the corresponding argument
64 to the built-in open() function: 0 means unbuffered, 1 means line
65 buffered, any other positive value means use a buffer of
66 (approximately) that size. A negative bufsize means to use the system
67 default, which usually means fully buffered. The default value for
68 bufsize is 0 (unbuffered).
70 stdin, stdout and stderr specify the executed programs' standard
71 input, standard output and standard error file handles, respectively.
72 Valid values are PIPE, an existing file descriptor (a positive
73 integer), an existing file object, and None. PIPE indicates that a
74 new pipe to the child should be created. With None, no redirection
75 will occur; the child's file handles will be inherited from the
76 parent. Additionally, stderr can be STDOUT, which indicates that the
77 stderr data from the applications should be captured into the same
78 file handle as for stdout.
80 If preexec_fn is set to a callable object, this object will be called
81 in the child process just before the child is executed.
83 If close_fds is true, all file descriptors except 0, 1 and 2 will be
84 closed before the child process is executed.
86 if shell is true, the specified command will be executed through the
89 If cwd is not None, the current directory will be changed to cwd
90 before the child is executed.
92 If env is not None, it defines the environment variables for the new
95 If universal_newlines is true, the file objects stdout and stderr are
96 opened as a text files, but lines may be terminated by any of '\n',
97 the Unix end-of-line convention, '\r', the Macintosh convention or
98 '\r\n', the Windows convention. All of these external representations
99 are seen as '\n' by the Python program. Note: This feature is only
100 available if Python is built with universal newline support (the
101 default). Also, the newlines attribute of the file objects stdout,
102 stdin and stderr are not updated by the communicate() method.
104 The startupinfo and creationflags, if given, will be passed to the
105 underlying CreateProcess() function. They can specify things such as
106 appearance of the main window and priority for the new process.
110 This module also defines two shortcut functions:
112 call(*args, **kwargs):
113 Run command with arguments. Wait for command to complete, then
114 return the returncode attribute.
116 The arguments are the same as for the Popen constructor. Example:
118 retcode = call(["ls", "-l"])
123 Exceptions raised in the child process, before the new program has
124 started to execute, will be re-raised in the parent. Additionally,
125 the exception object will have one extra attribute called
126 'child_traceback', which is a string containing traceback information
127 from the childs point of view.
129 The most common exception raised is OSError. This occurs, for
130 example, when trying to execute a non-existent file. Applications
131 should prepare for OSErrors.
133 A ValueError will be raised if Popen is called with invalid arguments.
138 Unlike some other popen functions, this implementation will never call
139 /bin/sh implicitly. This means that all characters, including shell
140 metacharacters, can safely be passed to child processes.
145 Instances of the Popen class have the following methods:
148 Check if child process has terminated. Returns returncode
152 Wait for child process to terminate. Returns returncode attribute.
154 communicate(input=None)
155 Interact with process: Send data to stdin. Read data from stdout
156 and stderr, until end-of-file is reached. Wait for process to
157 terminate. The optional stdin argument should be a string to be
158 sent to the child process, or None, if no data should be sent to
161 communicate() returns a tuple (stdout, stderr).
163 Note: The data read is buffered in memory, so do not use this
164 method if the data size is large or unlimited.
166 The following attributes are also available:
169 If the stdin argument is PIPE, this attribute is a file object
170 that provides input to the child process. Otherwise, it is None.
173 If the stdout argument is PIPE, this attribute is a file object
174 that provides output from the child process. Otherwise, it is
178 If the stderr argument is PIPE, this attribute is file object that
179 provides error output from the child process. Otherwise, it is
183 The process ID of the child process.
186 The child return code. A None value indicates that the process
187 hasn't terminated yet. A negative value -N indicates that the
188 child was terminated by signal N (UNIX only).
191 Replacing older functions with the subprocess module
192 ====================================================
193 In this section, "a ==> b" means that b can be used as a replacement
196 Note: All functions in this section fail (more or less) silently if
197 the executed program cannot be found; this module raises an OSError
200 In the following examples, we assume that the subprocess module is
201 imported with "from subprocess import *".
204 Replacing /bin/sh shell backquote
205 ---------------------------------
208 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
211 Replacing shell pipe line
212 -------------------------
213 output=`dmesg | grep hda`
215 p1 = Popen(["dmesg"], stdout=PIPE)
216 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
217 output = p2.communicate()[0]
220 Replacing os.system()
221 ---------------------
222 sts = os.system("mycmd" + " myarg")
224 p = Popen("mycmd" + " myarg", shell=True)
225 sts = os.waitpid(p.pid, 0)
229 * Calling the program through the shell is usually not required.
231 * It's easier to look at the returncode attribute than the
234 A more real-world example would look like this:
237 retcode = call("mycmd" + " myarg", shell=True)
239 print >>sys.stderr, "Child was terminated by signal", -retcode
241 print >>sys.stderr, "Child returned", retcode
243 print >>sys.stderr, "Execution failed:", e
250 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
252 pid = Popen(["/bin/mycmd", "myarg"]).pid
257 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
259 retcode = call(["/bin/mycmd", "myarg"])
264 os.spawnvp(os.P_NOWAIT, path, args)
266 Popen([path] + args[1:])
271 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
273 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
278 pipe = os.popen(cmd, mode='r', bufsize)
280 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
282 pipe = os.popen(cmd, mode=
'w', bufsize)
284 pipe = Popen(cmd, shell=
True, bufsize=bufsize, stdin=PIPE).stdin
287 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
289 p = Popen(cmd, shell=
True, bufsize=bufsize,
290 stdin=PIPE, stdout=PIPE, close_fds=
True)
291 (child_stdin, child_stdout) = (p.stdin, p.stdout)
296 child_stderr) = os.popen3(cmd, mode, bufsize)
298 p = Popen(cmd, shell=
True, bufsize=bufsize,
299 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=
True)
302 child_stderr) = (p.stdin, p.stdout, p.stderr)
305 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
307 p = Popen(cmd, shell=
True, bufsize=bufsize,
308 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=
True)
309 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
314 Note: If the cmd argument to popen2 functions
is a string, the command
315 is executed through /bin/sh. If it
is a list, the command
is directly
318 (child_stdout, child_stdin) = popen2.popen2(
"somestring", bufsize, mode)
320 p = Popen([
"somestring"], shell=
True, bufsize=bufsize
321 stdin=PIPE, stdout=PIPE, close_fds=
True)
322 (child_stdout, child_stdin) = (p.stdout, p.stdin)
325 (child_stdout, child_stdin) = popen2.popen2([
"mycmd",
"myarg"], bufsize, mode)
327 p = Popen([
"mycmd",
"myarg"], bufsize=bufsize,
328 stdin=PIPE, stdout=PIPE, close_fds=
True)
329 (child_stdout, child_stdin) = (p.stdout, p.stdin)
331 The popen2.Popen3
and popen3.Popen4 basically works
as subprocess.Popen,
334 * subprocess.Popen raises an exception
if the execution fails
335 * the capturestderr argument
is replaced with the stderr argument.
336 * stdin=PIPE
and stdout=PIPE must be specified.
337 * popen2 closes all filedescriptors by default, but you have to specify
338 close_fds=
True with subprocess.Popen.
344 mswindows = (sys.platform == "win32")
353 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
355 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
356 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
357 from win32api import GetCurrentProcess, DuplicateHandle, \
358 GetModuleFileName, GetVersion
359 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
360 from win32pipe import CreatePipe
361 from win32process import CreateProcess, STARTUPINFO, \
362 GetExitCodeProcess, STARTF_USESTDHANDLES, \
363 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
364 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
366 from _subprocess import *
383 __all__ = ["Popen", "PIPE", "STDOUT", "call"]
386 MAXFD = os.sysconf("SC_OPEN_MAX")
390 # True/False does not exist on 2.2.0
401 for inst in _active[:]:
408 def call(*args, **kwargs):
409 """Run command with arguments. Wait
for command to complete, then
410 return the returncode attribute.
412 The arguments are the same
as for the Popen constructor. Example:
414 retcode = call([
"ls",
"-l"])
416 return Popen(*args, **kwargs).wait()
419 def list2cmdline(seq):
421 Translate a sequence of arguments into a command line
422 string, using the same rules
as the MS C runtime:
424 1) Arguments are delimited by white space, which
is either a
427 2) A string surrounded by double quotation marks
is
428 interpreted
as a single argument, regardless of white space
429 contained within. A quoted string can be embedded
in an
432 3) A double quotation mark preceded by a backslash
is
433 interpreted
as a literal double quotation mark.
435 4) Backslashes are interpreted literally, unless they
436 immediately precede a double quotation mark.
438 5) If backslashes immediately precede a double quotation mark,
439 every pair of backslashes
is interpreted
as a literal
440 backslash. If the number of backslashes
is odd, the last
441 backslash escapes the next double quotation mark
as
446 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
452 # Add a space to separate this argument from the others
456 needquote = (" " in arg) or ("\t" in arg)
462 # Don't know if we need to double yet.
466 result.append('\\' * len(bs_buf) * 2)
472 result.extend(bs_buf)
476 # Add remaining backspaces, if any.
478 result.extend(bs_buf)
481 result.extend(bs_buf)
484 return ''.join(result)
489 def __init__(self, args, bufsize=0, executable=None,
490 stdin=None, stdout=None, stderr=None,
491 preexec_fn=None, close_fds=False, shell=False,
492 cwd=None, env=None, universal_newlines=False,
493 startupinfo=None, creationflags=0):
494 """Create new Popen instance.
"""
497 if not isinstance(bufsize, (int, long)):
498 raise TypeError("bufsize must be an integer")
501 if preexec_fn is not None:
502 raise ValueError("preexec_fn is not supported on Windows "
505 raise ValueError("close_fds is not supported on Windows "
509 if startupinfo is not None:
510 raise ValueError("startupinfo is only supported on Windows "
512 if creationflags != 0:
513 raise ValueError("creationflags is only supported on Windows "
520 self.returncode = None
521 self.universal_newlines = universal_newlines
523 # Input and output objects. The general principle is like
528 # p2cwrite ---stdin---> p2cread
529 # c2pread <--stdout--- c2pwrite
530 # errread <--stderr--- errwrite
532 # On POSIX, the child objects are file descriptors. On
533 # Windows, these are Windows file handles. The parent objects
534 # are file descriptors on both platforms. The parent objects
535 # are None when not using PIPEs. The child objects are None
536 # when not redirecting.
540 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
542 self._execute_child(args, executable, preexec_fn, close_fds,
543 cwd, env, universal_newlines,
544 startupinfo, creationflags, shell,
550 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
552 if universal_newlines:
553 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
555 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
557 if universal_newlines:
558 self.stderr = os.fdopen(errread, 'rU', bufsize)
560 self.stderr = os.fdopen(errread, 'rb', bufsize)
564 def _translate_newlines(self, data):
565 data = data.replace("\r\n", "\n")
566 data = data.replace("\r", "\n")
573 def _get_handles(self, stdin, stdout, stderr):
574 """Construct
and return tupel with IO objects:
575 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
577 if stdin is None and stdout is None and stderr is None:
578 return (None, None, None, None, None, None)
580 p2cread, p2cwrite = None, None
581 c2pread, c2pwrite = None, None
582 errread, errwrite = None, None
585 p2cread = GetStdHandle(STD_INPUT_HANDLE)
587 p2cread, p2cwrite = CreatePipe(None, 0)
588 # Detach and turn into fd
589 p2cwrite = p2cwrite.Detach()
590 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
591 elif isinstance(stdin, types.IntType):
592 p2cread = msvcrt.get_osfhandle(stdin)
594 # Assuming file-like object
595 p2cread = msvcrt.get_osfhandle(stdin.fileno())
596 p2cread = self._make_inheritable(p2cread)
599 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
601 c2pread, c2pwrite = CreatePipe(None, 0)
602 # Detach and turn into fd
603 c2pread = c2pread.Detach()
604 c2pread = msvcrt.open_osfhandle(c2pread, 0)
605 elif isinstance(stdout, types.IntType):
606 c2pwrite = msvcrt.get_osfhandle(stdout)
608 # Assuming file-like object
609 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
610 c2pwrite = self._make_inheritable(c2pwrite)
613 errwrite = GetStdHandle(STD_ERROR_HANDLE)
615 errread, errwrite = CreatePipe(None, 0)
616 # Detach and turn into fd
617 errread = errread.Detach()
618 errread = msvcrt.open_osfhandle(errread, 0)
619 elif stderr == STDOUT:
621 elif isinstance(stderr, types.IntType):
622 errwrite = msvcrt.get_osfhandle(stderr)
624 # Assuming file-like object
625 errwrite = msvcrt.get_osfhandle(stderr.fileno())
626 errwrite = self._make_inheritable(errwrite)
628 return (p2cread, p2cwrite,
632 def _make_inheritable(self, handle):
633 """Return a duplicate of handle, which
is inheritable
"""
634 return DuplicateHandle(GetCurrentProcess(), handle,
635 GetCurrentProcess(), 0, 1,
636 DUPLICATE_SAME_ACCESS)
638 def _find_w9xpopen(self):
639 """Find
and return absolut path to w9xpopen.exe
"""
640 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
642 if not os.path.exists(w9xpopen):
643 # Eeek - file-not-found - possibly an embedding
644 # situation - see if we can locate it in sys.exec_prefix
645 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
647 if not os.path.exists(w9xpopen):
648 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
649 "needed for Popen to work with your "
650 "shell or platform.")
653 def _execute_child(self, args, executable, preexec_fn, close_fds,
654 cwd, env, universal_newlines,
655 startupinfo, creationflags, shell,
659 """Execute program (MS Windows version)
"""
661 if not isinstance(args, types.StringTypes):
662 args = list2cmdline(args)
664 # Process startup details
665 if startupinfo is None:
666 startupinfo = STARTUPINFO()
667 if None not in (p2cread, c2pwrite, errwrite):
668 startupinfo.dwFlags |= STARTF_USESTDHANDLES
669 startupinfo.hStdInput = p2cread
670 startupinfo.hStdOutput = c2pwrite
671 startupinfo.hStdError = errwrite
674 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
675 startupinfo.wShowWindow = SW_HIDE
676 comspec = os.environ.get("COMSPEC", "cmd.exe")
677 args = comspec + " /c " + args
678 if (GetVersion() >= 0x80000000 or
679 os.path.basename(comspec).lower() == "command.com"):
680 # Win9x, or using command.com on NT. We need to
681 # use the w9xpopen intermediate program. For more
682 # information, see KB Q150956
683 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
684 w9xpopen = self._find_w9xpopen()
685 args = '"%s" %s' % (w9xpopen, args)
686 # Not passing CREATE_NEW_CONSOLE has been known to
687 # cause random failures on win9x. Specifically a
688 # dialog: "Your program accessed mem currently in
689 # use at xxx" and a hopeful warning about the
690 # stability of your system. Cost is Ctrl+C wont
692 creationflags |= CREATE_NEW_CONSOLE
696 hp, ht, pid, tid = CreateProcess(executable, args,
697 # no special security
699 # must inherit handles to pass std
706 except pywintypes.error as e:
707 # Translate pywintypes.error to WindowsError, which is
708 # a subclass of OSError. FIXME: We should really
709 # translate errno using _sys_errlist (or simliar), but
710 # how can this be done from Python?
711 raise WindowsError(*e.args)
713 # Retain the process handle, but close the thread handle
718 # Child is launched. Close the parent's copy of those pipe
719 # handles that only the child should have open. You need
720 # to make sure that no handles to the write end of the
721 # output pipe are maintained in this process or else the
722 # pipe will not close when the child process exits and the
723 # ReadFile will hang.
724 if p2cread is not None:
726 if c2pwrite is not None:
728 if errwrite is not None:
732 """Check
if child process has terminated. Returns returncode
734 if self.returncode is None:
735 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
736 self.returncode = GetExitCodeProcess(self._handle)
738 return self.returncode
741 """Wait
for child process to terminate. Returns returncode
743 if self.returncode is None:
744 obj = WaitForSingleObject(self._handle, INFINITE)
745 self.returncode = GetExitCodeProcess(self._handle)
747 return self.returncode
749 def _readerthread(self, fh, buffer):
750 buffer.append(fh.read())
752 def communicate(self, input=None):
753 """Interact with process: Send data to stdin. Read data
from
754 stdout
and stderr, until end-of-file
is reached. Wait
for
755 process to terminate. The optional input argument should be a
756 string to be sent to the child process,
or None,
if no data
757 should be sent to the child.
759 communicate() returns a tuple (stdout, stderr).
"""
760 stdout = None # Return
761 stderr = None # Return
765 stdout_thread = threading.Thread(target=self._readerthread,
766 args=(self.stdout, stdout))
767 stdout_thread.setDaemon(True)
768 stdout_thread.start()
771 stderr_thread = threading.Thread(target=self._readerthread,
772 args=(self.stderr, stderr))
773 stderr_thread.setDaemon(True)
774 stderr_thread.start()
777 if input is not None:
778 self.stdin.write(input)
786 # All data exchanged. Translate lists into strings.
787 if stdout is not None:
789 if stderr is not None:
792 # Translate newlines, if requested. We cannot let the file
793 # object do the translation: It is based on stdio, which is
794 # impossible to combine with select (unless forcing no
796 if self.universal_newlines and hasattr(open, 'newlines'):
798 stdout = self._translate_newlines(stdout)
800 stderr = self._translate_newlines(stderr)
803 return (stdout, stderr)
809 def _get_handles(self, stdin, stdout, stderr):
810 """Construct
and return tupel with IO objects:
811 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
813 p2cread, p2cwrite = None, None
814 c2pread, c2pwrite = None, None
815 errread, errwrite = None, None
820 p2cread, p2cwrite = os.pipe()
821 elif isinstance(stdin, types.IntType):
824 # Assuming file-like object
825 p2cread = stdin.fileno()
830 c2pread, c2pwrite = os.pipe()
831 elif isinstance(stdout, types.IntType):
834 # Assuming file-like object
835 c2pwrite = stdout.fileno()
840 errread, errwrite = os.pipe()
841 elif stderr == STDOUT:
843 elif isinstance(stderr, types.IntType):
846 # Assuming file-like object
847 errwrite = stderr.fileno()
849 return (p2cread, p2cwrite,
853 def _set_cloexec_flag(self, fd):
855 cloexec_flag = fcntl.FD_CLOEXEC
856 except AttributeError:
859 old = fcntl.fcntl(fd, fcntl.F_GETFD)
860 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
862 def _close_fds(self, but):
863 for i in xrange(3, MAXFD):
871 def _execute_child(self, args, executable, preexec_fn, close_fds,
872 cwd, env, universal_newlines,
873 startupinfo, creationflags, shell,
877 """Execute program (POSIX version)
"""
879 if isinstance(args, types.StringTypes):
883 args = ["/bin/sh", "-c"] + args
885 if executable is None:
888 # For transferring possible exec failure from child to parent
889 # The first char specifies the exception type: 0 means
890 # OSError, 1 means some other error.
891 errpipe_read, errpipe_write = os.pipe()
892 self._set_cloexec_flag(errpipe_write)
898 # Close parent's pipe ends
905 os.close(errpipe_read)
915 # Close pipe fds. Make sure we doesn't close the same
919 if c2pwrite and c2pwrite not in (p2cread,):
921 if errwrite and errwrite not in (p2cread, c2pwrite):
924 # Close all other fds, if asked for
926 self._close_fds(but=errpipe_write)
935 os.execvp(executable, args)
937 os.execvpe(executable, args, env)
940 exc_type, exc_value, tb = sys.exc_info()
941 # Save the traceback and attach it to the exception object
942 exc_lines = traceback.format_exception(exc_type,
945 exc_value.child_traceback = ''.join(exc_lines)
946 os.write(errpipe_write, pickle.dumps(exc_value))
948 # This exitcode won't be reported to applications, so it
949 # really doesn't matter what we return.
953 os.close(errpipe_write)
954 if p2cread and p2cwrite:
956 if c2pwrite and c2pread:
958 if errwrite and errread:
961 # Wait for exec to fail or succeed; possibly raising exception
962 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
963 os.close(errpipe_read)
965 os.waitpid(self.pid, 0)
966 child_exception = pickle.loads(data)
967 raise child_exception
969 def _handle_exitstatus(self, sts):
970 if os.WIFSIGNALED(sts):
971 self.returncode = -os.WTERMSIG(sts)
972 elif os.WIFEXITED(sts):
973 self.returncode = os.WEXITSTATUS(sts)
975 # Should never happen
976 raise RuntimeError("Unknown child exit status!")
981 """Check
if child process has terminated. Returns returncode
983 if self.returncode is None:
985 pid, sts = os.waitpid(self.pid, os.WNOHANG)
987 self._handle_exitstatus(sts)
990 return self.returncode
993 """Wait
for child process to terminate. Returns returncode
995 if self.returncode is None:
996 pid, sts = os.waitpid(self.pid, 0)
997 self._handle_exitstatus(sts)
998 return self.returncode
1000 def communicate(self, input=None):
1001 """Interact with process: Send data to stdin. Read data
from
1002 stdout
and stderr, until end-of-file
is reached. Wait
for
1003 process to terminate. The optional input argument should be a
1004 string to be sent to the child process,
or None,
if no data
1005 should be sent to the child.
1007 communicate() returns a tuple (stdout, stderr).
"""
1010 stdout = None # Return
1011 stderr = None # Return
1014 # Flush stdio buffer. This might block, if the user has
1015 # been writing to .stdin in an uncontrolled fashion.
1018 write_set.append(self.stdin)
1022 read_set.append(self.stdout)
1025 read_set.append(self.stderr)
1028 while read_set or write_set:
1029 rlist, wlist, xlist = select.select(read_set, write_set, [])
1031 if self.stdin in wlist:
1032 # When select has indicated that the file is writable,
1033 # we can write up to PIPE_BUF bytes without risk
1034 # blocking. POSIX defines PIPE_BUF >= 512
1035 bytes_written = os.write(self.stdin.fileno(), input[:512])
1036 input = input[bytes_written:]
1039 write_set.remove(self.stdin)
1041 if self.stdout in rlist:
1042 data = os.read(self.stdout.fileno(), 1024)
1045 read_set.remove(self.stdout)
1048 if self.stderr in rlist:
1049 data = os.read(self.stderr.fileno(), 1024)
1052 read_set.remove(self.stderr)
1055 # All data exchanged. Translate lists into strings.
1056 if stdout is not None:
1057 stdout = ''.join(stdout)
1058 if stderr is not None:
1059 stderr = ''.join(stderr)
1061 # Translate newlines, if requested. We cannot let the file
1062 # object do the translation: It is based on stdio, which is
1063 # impossible to combine with select (unless forcing no
1065 if self.universal_newlines and hasattr(open, 'newlines'):
1067 stdout = self._translate_newlines(stdout)
1069 stderr = self._translate_newlines(stderr)
1072 return (stdout, stderr)
1077 # Example 1: Simple redirection: Get process list
1079 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1080 print "Process list:"
1084 # Example 2: Change uid before executing child
1086 if os.getuid() == 0:
1087 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1091 # Example 3: Connecting several subprocesses
1093 print "Looking for 'hda'..."
1094 p1 = Popen(["dmesg"], stdout=PIPE)
1095 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1096 print repr(p2.communicate()[0])
1099 # Example 4: Catch execution error
1102 print "Trying a weird file..."
1104 print Popen(["/this/path/does/not/exist"]).communicate()
1105 except OSError as e:
1106 if e.errno == errno.ENOENT:
1107 print "The file didn't exist. I thought so..."
1108 print "Child traceback:"
1109 print e.child_traceback
1111 print "Error", e.errno
1113 print >>sys.stderr, "Gosh. No error."
1116 def _demo_windows():
1118 # Example 1: Connecting several subprocesses
1120 print "Looking for 'PROMPT' in set output..."
1121 p1 = Popen("set", stdout=PIPE, shell=True)
1122 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1123 print repr(p2.communicate()[0])
1126 # Example 2: Simple execution of program
1128 print "Executing calc..."
1133 if __name__ == "__main__":