Clarify dual license status of subprocess.py file.
[git/jrn.git] / compat / subprocess.py
blob93323dfc0a6e708ec781150740506186eded9ab0
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
18 # permission.
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:
37 os.system
38 os.spawn*
39 os.popen*
40 popen2.*
41 commands.*
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):
59 Arguments are:
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
106 shell.
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
112 process.
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.
126 (Windows only)
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"])
140 Exceptions
141 ----------
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.
155 Security
156 --------
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.
162 Popen objects
163 =============
164 Instances of the Popen class have the following methods:
166 poll()
167 Check if child process has terminated. Returns returncode
168 attribute.
170 wait()
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
178 the child.
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:
187 stdin
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.
191 stdout
192 If the stdout argument is PIPE, this attribute is a file object
193 that provides output from the child process. Otherwise, it is
194 None.
196 stderr
197 If the stderr argument is PIPE, this attribute is file object that
198 provides error output from the child process. Otherwise, it is
199 None.
202 The process ID of the child process.
204 returncode
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
213 for a.
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
217 exception.
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 ---------------------------------
225 output=`mycmd myarg`
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)
246 Note:
248 * Calling the program through the shell is usually not required.
250 * It's easier to look at the returncode attribute than the
251 exitstatus.
253 A more real-world example would look like this:
255 try:
256 retcode = call("mycmd" + " myarg", shell=True)
257 if retcode < 0:
258 print >>sys.stderr, "Child was terminated by signal", -retcode
259 else:
260 print >>sys.stderr, "Child returned", retcode
261 except OSError, e:
262 print >>sys.stderr, "Execution failed:", e
265 Replacing os.spawn*
266 -------------------
267 P_NOWAIT example:
269 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
271 pid = Popen(["/bin/mycmd", "myarg"]).pid
274 P_WAIT example:
276 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
278 retcode = call(["/bin/mycmd", "myarg"])
281 Vector example:
283 os.spawnvp(os.P_NOWAIT, path, args)
285 Popen([path] + args[1:])
288 Environment example:
290 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
292 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
295 Replacing os.popen*
296 -------------------
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)
313 (child_stdin,
314 child_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)
319 (child_stdin,
320 child_stdout,
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)
331 Replacing popen2.*
332 ------------------
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
335 executed.
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,
351 except that:
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.
362 import sys
363 mswindows = (sys.platform == "win32")
365 import os
366 import types
367 import traceback
369 if mswindows:
370 import threading
371 import msvcrt
372 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
373 import pywintypes
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
384 else:
385 from _subprocess import *
386 class STARTUPINFO:
387 dwFlags = 0
388 hStdInput = None
389 hStdOutput = None
390 hStdError = None
391 class pywintypes:
392 error = IOError
393 else:
394 import select
395 import errno
396 import fcntl
397 import pickle
399 __all__ = ["Popen", "PIPE", "STDOUT", "call"]
401 try:
402 MAXFD = os.sysconf("SC_OPEN_MAX")
403 except:
404 MAXFD = 256
406 # True/False does not exist on 2.2.0
407 try:
408 False
409 except NameError:
410 False = 0
411 True = 1
413 _active = []
415 def _cleanup():
416 for inst in _active[:]:
417 inst.poll()
419 PIPE = -1
420 STDOUT = -2
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
440 space or a tab.
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
445 argument.
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
457 described in rule 3.
460 # See
461 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
462 result = []
463 needquote = False
464 for arg in seq:
465 bs_buf = []
467 # Add a space to separate this argument from the others
468 if result:
469 result.append(' ')
471 needquote = (" " in arg) or ("\t" in arg)
472 if needquote:
473 result.append('"')
475 for c in arg:
476 if c == '\\':
477 # Don't know if we need to double yet.
478 bs_buf.append(c)
479 elif c == '"':
480 # Double backspaces.
481 result.append('\\' * len(bs_buf)*2)
482 bs_buf = []
483 result.append('\\"')
484 else:
485 # Normal char
486 if bs_buf:
487 result.extend(bs_buf)
488 bs_buf = []
489 result.append(c)
491 # Add remaining backspaces, if any.
492 if bs_buf:
493 result.extend(bs_buf)
495 if needquote:
496 result.extend(bs_buf)
497 result.append('"')
499 return ''.join(result)
502 class Popen(object):
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."""
509 _cleanup()
511 if not isinstance(bufsize, (int, long)):
512 raise TypeError("bufsize must be an integer")
514 if mswindows:
515 if preexec_fn is not None:
516 raise ValueError("preexec_fn is not supported on Windows "
517 "platforms")
518 if close_fds:
519 raise ValueError("close_fds is not supported on Windows "
520 "platforms")
521 else:
522 # POSIX
523 if startupinfo is not None:
524 raise ValueError("startupinfo is only supported on Windows "
525 "platforms")
526 if creationflags != 0:
527 raise ValueError("creationflags is only supported on Windows "
528 "platforms")
530 self.stdin = None
531 self.stdout = None
532 self.stderr = None
533 self.pid = None
534 self.returncode = None
535 self.universal_newlines = universal_newlines
537 # Input and output objects. The general principle is like
538 # this:
540 # Parent Child
541 # ------ -----
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.
552 (p2cread, p2cwrite,
553 c2pread, c2pwrite,
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,
559 p2cread, p2cwrite,
560 c2pread, c2pwrite,
561 errread, errwrite)
563 if p2cwrite:
564 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
565 if c2pread:
566 if universal_newlines:
567 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
568 else:
569 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
570 if errread:
571 if universal_newlines:
572 self.stderr = os.fdopen(errread, 'rU', bufsize)
573 else:
574 self.stderr = os.fdopen(errread, 'rb', bufsize)
576 _active.append(self)
579 def _translate_newlines(self, data):
580 data = data.replace("\r\n", "\n")
581 data = data.replace("\r", "\n")
582 return data
585 if mswindows:
587 # Windows methods
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
600 if stdin == None:
601 p2cread = GetStdHandle(STD_INPUT_HANDLE)
602 elif stdin == PIPE:
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)
609 else:
610 # Assuming file-like object
611 p2cread = msvcrt.get_osfhandle(stdin.fileno())
612 p2cread = self._make_inheritable(p2cread)
614 if stdout == None:
615 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
616 elif stdout == PIPE:
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)
623 else:
624 # Assuming file-like object
625 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
626 c2pwrite = self._make_inheritable(c2pwrite)
628 if stderr == None:
629 errwrite = GetStdHandle(STD_ERROR_HANDLE)
630 elif stderr == PIPE:
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:
636 errwrite = c2pwrite
637 elif type(stderr) == types.IntType:
638 errwrite = msvcrt.get_osfhandle(stderr)
639 else:
640 # Assuming file-like object
641 errwrite = msvcrt.get_osfhandle(stderr.fileno())
642 errwrite = self._make_inheritable(errwrite)
644 return (p2cread, p2cwrite,
645 c2pread, c2pwrite,
646 errread, errwrite)
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)),
659 "w9xpopen.exe")
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),
664 "w9xpopen.exe")
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.")
669 return w9xpopen
672 def _execute_child(self, args, executable, preexec_fn, close_fds,
673 cwd, env, universal_newlines,
674 startupinfo, creationflags, shell,
675 p2cread, p2cwrite,
676 c2pread, c2pwrite,
677 errread, errwrite):
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
693 if shell:
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
711 # kill children.
712 creationflags |= CREATE_NEW_CONSOLE
714 # Start the process
715 try:
716 hp, ht, pid, tid = CreateProcess(executable, args,
717 # no special security
718 None, None,
719 # must inherit handles to pass std
720 # handles
722 creationflags,
723 env,
724 cwd,
725 startupinfo)
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
734 self._handle = hp
735 self.pid = pid
736 ht.Close()
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.
744 if p2cread != None:
745 p2cread.Close()
746 if c2pwrite != None:
747 c2pwrite.Close()
748 if errwrite != None:
749 errwrite.Close()
752 def poll(self):
753 """Check if child process has terminated. Returns returncode
754 attribute."""
755 if self.returncode == None:
756 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
757 self.returncode = GetExitCodeProcess(self._handle)
758 _active.remove(self)
759 return self.returncode
762 def wait(self):
763 """Wait for child process to terminate. Returns returncode
764 attribute."""
765 if self.returncode == None:
766 obj = WaitForSingleObject(self._handle, INFINITE)
767 self.returncode = GetExitCodeProcess(self._handle)
768 _active.remove(self)
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
787 if self.stdout:
788 stdout = []
789 stdout_thread = threading.Thread(target=self._readerthread,
790 args=(self.stdout, stdout))
791 stdout_thread.setDaemon(True)
792 stdout_thread.start()
793 if self.stderr:
794 stderr = []
795 stderr_thread = threading.Thread(target=self._readerthread,
796 args=(self.stderr, stderr))
797 stderr_thread.setDaemon(True)
798 stderr_thread.start()
800 if self.stdin:
801 if input != None:
802 self.stdin.write(input)
803 self.stdin.close()
805 if self.stdout:
806 stdout_thread.join()
807 if self.stderr:
808 stderr_thread.join()
810 # All data exchanged. Translate lists into strings.
811 if stdout != None:
812 stdout = stdout[0]
813 if stderr != None:
814 stderr = stderr[0]
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
819 # buffering).
820 if self.universal_newlines and hasattr(open, 'newlines'):
821 if stdout:
822 stdout = self._translate_newlines(stdout)
823 if stderr:
824 stderr = self._translate_newlines(stderr)
826 self.wait()
827 return (stdout, stderr)
829 else:
831 # POSIX methods
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
841 if stdin == None:
842 pass
843 elif stdin == PIPE:
844 p2cread, p2cwrite = os.pipe()
845 elif type(stdin) == types.IntType:
846 p2cread = stdin
847 else:
848 # Assuming file-like object
849 p2cread = stdin.fileno()
851 if stdout == None:
852 pass
853 elif stdout == PIPE:
854 c2pread, c2pwrite = os.pipe()
855 elif type(stdout) == types.IntType:
856 c2pwrite = stdout
857 else:
858 # Assuming file-like object
859 c2pwrite = stdout.fileno()
861 if stderr == None:
862 pass
863 elif stderr == PIPE:
864 errread, errwrite = os.pipe()
865 elif stderr == STDOUT:
866 errwrite = c2pwrite
867 elif type(stderr) == types.IntType:
868 errwrite = stderr
869 else:
870 # Assuming file-like object
871 errwrite = stderr.fileno()
873 return (p2cread, p2cwrite,
874 c2pread, c2pwrite,
875 errread, errwrite)
878 def _set_cloexec_flag(self, fd):
879 try:
880 cloexec_flag = fcntl.FD_CLOEXEC
881 except AttributeError:
882 cloexec_flag = 1
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):
890 if i == but:
891 continue
892 try:
893 os.close(i)
894 except:
895 pass
898 def _execute_child(self, args, executable, preexec_fn, close_fds,
899 cwd, env, universal_newlines,
900 startupinfo, creationflags, shell,
901 p2cread, p2cwrite,
902 c2pread, c2pwrite,
903 errread, errwrite):
904 """Execute program (POSIX version)"""
906 if isinstance(args, types.StringTypes):
907 args = [args]
909 if shell:
910 args = ["/bin/sh", "-c"] + args
912 if executable == None:
913 executable = args[0]
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)
921 self.pid = os.fork()
922 if self.pid == 0:
923 # Child
924 try:
925 # Close parent's pipe ends
926 if p2cwrite:
927 os.close(p2cwrite)
928 if c2pread:
929 os.close(c2pread)
930 if errread:
931 os.close(errread)
932 os.close(errpipe_read)
934 # Dup fds for child
935 if p2cread:
936 os.dup2(p2cread, 0)
937 if c2pwrite:
938 os.dup2(c2pwrite, 1)
939 if errwrite:
940 os.dup2(errwrite, 2)
942 # Close pipe fds. Make sure we doesn't close the same
943 # fd more than once.
944 if p2cread:
945 os.close(p2cread)
946 if c2pwrite and c2pwrite not in (p2cread,):
947 os.close(c2pwrite)
948 if errwrite and errwrite not in (p2cread, c2pwrite):
949 os.close(errwrite)
951 # Close all other fds, if asked for
952 if close_fds:
953 self._close_fds(but=errpipe_write)
955 if cwd != None:
956 os.chdir(cwd)
958 if preexec_fn:
959 apply(preexec_fn)
961 if env == None:
962 os.execvp(executable, args)
963 else:
964 os.execvpe(executable, args, env)
966 except:
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,
970 exc_value,
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.
977 os._exit(255)
979 # Parent
980 os.close(errpipe_write)
981 if p2cread and p2cwrite:
982 os.close(p2cread)
983 if c2pwrite and c2pread:
984 os.close(c2pwrite)
985 if errwrite and errread:
986 os.close(errwrite)
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)
991 if data != "":
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)
1002 else:
1003 # Should never happen
1004 raise RuntimeError("Unknown child exit status!")
1006 _active.remove(self)
1009 def poll(self):
1010 """Check if child process has terminated. Returns returncode
1011 attribute."""
1012 if self.returncode == None:
1013 try:
1014 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1015 if pid == self.pid:
1016 self._handle_exitstatus(sts)
1017 except os.error:
1018 pass
1019 return self.returncode
1022 def wait(self):
1023 """Wait for child process to terminate. Returns returncode
1024 attribute."""
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)."""
1039 read_set = []
1040 write_set = []
1041 stdout = None # Return
1042 stderr = None # Return
1044 if self.stdin:
1045 # Flush stdio buffer. This might block, if the user has
1046 # been writing to .stdin in an uncontrolled fashion.
1047 self.stdin.flush()
1048 if input:
1049 write_set.append(self.stdin)
1050 else:
1051 self.stdin.close()
1052 if self.stdout:
1053 read_set.append(self.stdout)
1054 stdout = []
1055 if self.stderr:
1056 read_set.append(self.stderr)
1057 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:]
1068 if not input:
1069 self.stdin.close()
1070 write_set.remove(self.stdin)
1072 if self.stdout in rlist:
1073 data = os.read(self.stdout.fileno(), 1024)
1074 if data == "":
1075 self.stdout.close()
1076 read_set.remove(self.stdout)
1077 stdout.append(data)
1079 if self.stderr in rlist:
1080 data = os.read(self.stderr.fileno(), 1024)
1081 if data == "":
1082 self.stderr.close()
1083 read_set.remove(self.stderr)
1084 stderr.append(data)
1086 # All data exchanged. Translate lists into strings.
1087 if stdout != None:
1088 stdout = ''.join(stdout)
1089 if stderr != None:
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
1095 # buffering).
1096 if self.universal_newlines and hasattr(open, 'newlines'):
1097 if stdout:
1098 stdout = self._translate_newlines(stdout)
1099 if stderr:
1100 stderr = self._translate_newlines(stderr)
1102 self.wait()
1103 return (stdout, stderr)
1106 def _demo_posix():
1108 # Example 1: Simple redirection: Get process list
1110 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1111 print "Process list:"
1112 print plist
1115 # Example 2: Change uid before executing child
1117 if os.getuid() == 0:
1118 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1119 p.wait()
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
1132 print
1133 print "Trying a weird file..."
1134 try:
1135 print Popen(["/this/path/does/not/exist"]).communicate()
1136 except OSError, e:
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
1141 else:
1142 print "Error", e.errno
1143 else:
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..."
1160 p = Popen("calc")
1161 p.wait()
1164 if __name__ == "__main__":
1165 if mswindows:
1166 _demo_windows()
1167 else:
1168 _demo_posix()