Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Lib/subprocess.py

    r2 r388  
    22#
    33# For more information about this module, see PEP 324.
    4 #
    5 # This module should remain compatible with Python 2.2, see PEP 291.
    64#
    75# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
     
    108106
    109107
    110 This module also defines two shortcut functions:
     108This module also defines some shortcut functions:
    111109
    112110call(*popenargs, **kwargs):
     
    127125
    128126    check_call(["ls", "-l"])
     127
     128check_output(*popenargs, **kwargs):
     129    Run command with arguments and return its output as a byte string.
     130
     131    If the exit code was non-zero it raises a CalledProcessError.  The
     132    CalledProcessError object will have the return code in the returncode
     133    attribute and output in the output attribute.
     134
     135    The arguments are the same as for the Popen constructor.  Example:
     136
     137    output = check_output(["ls", "-l", "/dev/null"])
     138
    129139
    130140Exceptions
     
    134144the exception object will have one extra attribute called
    135145'child_traceback', which is a string containing traceback information
    136 from the childs point of view.
     146from the child's point of view.
    137147
    138148The most common exception raised is OSError.  This occurs, for
     
    142152A ValueError will be raised if Popen is called with invalid arguments.
    143153
    144 check_call() will raise CalledProcessError, if the called process
    145 returns a non-zero return code.
     154check_call() and check_output() will raise CalledProcessError, if the
     155called process returns a non-zero return code.
    146156
    147157
     
    338348...
    339349rc = pipe.close()
    340 if rc != None and rc % 256:
     350if rc is not None and rc % 256:
    341351    print "There were some errors"
    342352==>
     
    385395import gc
    386396import signal
     397import errno
    387398
    388399# Exception classes used by this module.
    389400class CalledProcessError(Exception):
    390     """This exception is raised when a process run by check_call() returns
    391     a non-zero exit status.  The exit status will be stored in the
    392     returncode attribute."""
    393     def __init__(self, returncode, cmd):
     401    """This exception is raised when a process run by check_call() or
     402    check_output() returns a non-zero exit status.
     403    The exit status will be stored in the returncode attribute;
     404    check_output() will also store the output in the output attribute.
     405    """
     406    def __init__(self, returncode, cmd, output=None):
    394407        self.returncode = returncode
    395408        self.cmd = cmd
     409        self.output = output
    396410    def __str__(self):
    397411        return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
     
    401415    import threading
    402416    import msvcrt
    403     if 0: # <-- change this to use pywin32 instead of the _subprocess driver
    404         import pywintypes
    405         from win32api import GetStdHandle, STD_INPUT_HANDLE, \
    406                              STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
    407         from win32api import GetCurrentProcess, DuplicateHandle, \
    408                              GetModuleFileName, GetVersion
    409         from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
    410         from win32pipe import CreatePipe
    411         from win32process import CreateProcess, STARTUPINFO, \
    412                                  GetExitCodeProcess, STARTF_USESTDHANDLES, \
    413                                  STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
    414         from win32process import TerminateProcess
    415         from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
    416     else:
    417         from _subprocess import *
    418         class STARTUPINFO:
    419             dwFlags = 0
    420             hStdInput = None
    421             hStdOutput = None
    422             hStdError = None
    423             wShowWindow = 0
    424         class pywintypes:
    425             error = IOError
     417    import _subprocess
     418    class STARTUPINFO:
     419        dwFlags = 0
     420        hStdInput = None
     421        hStdOutput = None
     422        hStdError = None
     423        wShowWindow = 0
     424    class pywintypes:
     425        error = IOError
    426426else:
    427427    import select
    428     import errno
     428    _has_poll = hasattr(select, 'poll')
    429429    import fcntl
    430430    import pickle
    431431
    432 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
    433 
     432    # When select or poll has indicated that the file is writable,
     433    # we can write up to _PIPE_BUF bytes without risk of blocking.
     434    # POSIX defines PIPE_BUF as >= 512.
     435    _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
     436
     437
     438__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
     439           "check_output", "CalledProcessError"]
     440
     441if mswindows:
     442    from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
     443                             STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
     444                             STD_ERROR_HANDLE, SW_HIDE,
     445                             STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
     446
     447    __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
     448                    "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
     449                    "STD_ERROR_HANDLE", "SW_HIDE",
     450                    "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
    434451try:
    435452    MAXFD = os.sysconf("SC_OPEN_MAX")
     
    437454    MAXFD = 256
    438455
    439 # True/False does not exist on 2.2.0
    440 #try:
    441 #    False
    442 #except NameError:
    443 #    False = 0
    444 #    True = 1
    445 
    446456_active = []
    447457
    448458def _cleanup():
    449459    for inst in _active[:]:
    450         if inst._internal_poll(_deadstate=sys.maxint) >= 0:
     460        res = inst._internal_poll(_deadstate=sys.maxint)
     461        if res is not None:
    451462            try:
    452463                _active.remove(inst)
     
    464475        try:
    465476            return func(*args)
    466         except OSError, e:
     477        except (OSError, IOError) as e:
    467478            if e.errno == errno.EINTR:
    468479                continue
    469480            raise
     481
     482
     483# XXX This function is only used by multiprocessing and the test suite,
     484# but it's here so that it can be imported when Python is compiled without
     485# threads.
     486
     487def _args_from_interpreter_flags():
     488    """Return a list of command-line arguments reproducing the current
     489    settings in sys.flags and sys.warnoptions."""
     490    flag_opt_map = {
     491        'debug': 'd',
     492        # 'inspect': 'i',
     493        # 'interactive': 'i',
     494        'optimize': 'O',
     495        'dont_write_bytecode': 'B',
     496        'no_user_site': 's',
     497        'no_site': 'S',
     498        'ignore_environment': 'E',
     499        'verbose': 'v',
     500        'bytes_warning': 'b',
     501        'hash_randomization': 'R',
     502        'py3k_warning': '3',
     503    }
     504    args = []
     505    for flag, opt in flag_opt_map.items():
     506        v = getattr(sys.flags, flag)
     507        if v > 0:
     508            args.append('-' + opt * v)
     509    for opt in sys.warnoptions:
     510        args.append('-W' + opt)
     511    return args
    470512
    471513
     
    492534    """
    493535    retcode = call(*popenargs, **kwargs)
    494     cmd = kwargs.get("args")
    495     if cmd is None:
    496         cmd = popenargs[0]
    497536    if retcode:
     537        cmd = kwargs.get("args")
     538        if cmd is None:
     539            cmd = popenargs[0]
    498540        raise CalledProcessError(retcode, cmd)
    499     return retcode
     541    return 0
     542
     543
     544def check_output(*popenargs, **kwargs):
     545    r"""Run command with arguments and return its output as a byte string.
     546
     547    If the exit code was non-zero it raises a CalledProcessError.  The
     548    CalledProcessError object will have the return code in the returncode
     549    attribute and output in the output attribute.
     550
     551    The arguments are the same as for the Popen constructor.  Example:
     552
     553    >>> check_output(["ls", "-l", "/dev/null"])
     554    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
     555
     556    The stdout argument is not allowed as it is used internally.
     557    To capture standard error in the result, use stderr=STDOUT.
     558
     559    >>> check_output(["/bin/sh", "-c",
     560    ...               "ls -l non_existent_file ; exit 0"],
     561    ...              stderr=STDOUT)
     562    'ls: non_existent_file: No such file or directory\n'
     563    """
     564    if 'stdout' in kwargs:
     565        raise ValueError('stdout argument not allowed, it will be overridden.')
     566    process = Popen(stdout=PIPE, *popenargs, **kwargs)
     567    output, unused_err = process.communicate()
     568    retcode = process.poll()
     569    if retcode:
     570        cmd = kwargs.get("args")
     571        if cmd is None:
     572            cmd = popenargs[0]
     573        raise CalledProcessError(retcode, cmd, output=output)
     574    return output
    500575
    501576
     
    510585    2) A string surrounded by double quotation marks is
    511586       interpreted as a single argument, regardless of white space
    512        or pipe characters contained within.  A quoted string can be
    513        embedded in an argument.
     587       contained within.  A quoted string can be embedded in an
     588       argument.
    514589
    515590    3) A double quotation mark preceded by a backslash is
     
    539614            result.append(' ')
    540615
    541         needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
     616        needquote = (" " in arg) or ("\t" in arg) or not arg
    542617        if needquote:
    543618            result.append('"')
     
    624699        (p2cread, p2cwrite,
    625700         c2pread, c2pwrite,
    626          errread, errwrite) = self._get_handles(stdin, stdout, stderr)
    627 
    628         self._execute_child(args, executable, preexec_fn, close_fds,
    629                             cwd, env, universal_newlines,
    630                             startupinfo, creationflags, shell,
    631                             p2cread, p2cwrite,
    632                             c2pread, c2pwrite,
    633                             errread, errwrite)
     701         errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
     702
     703        try:
     704            self._execute_child(args, executable, preexec_fn, close_fds,
     705                                cwd, env, universal_newlines,
     706                                startupinfo, creationflags, shell, to_close,
     707                                p2cread, p2cwrite,
     708                                c2pread, c2pwrite,
     709                                errread, errwrite)
     710        except Exception:
     711            # Preserve original exception in case os.close raises.
     712            exc_type, exc_value, exc_trace = sys.exc_info()
     713
     714            for fd in to_close:
     715                try:
     716                    if mswindows:
     717                        fd.Close()
     718                    else:
     719                        os.close(fd)
     720                except EnvironmentError:
     721                    pass
     722
     723            raise exc_type, exc_value, exc_trace
    634724
    635725        if mswindows:
     
    661751
    662752
    663     def __del__(self, sys=sys):
    664         if not self._child_created:
     753    def __del__(self, _maxint=sys.maxint, _active=_active):
     754        # If __init__ hasn't had a chance to execute (e.g. if it
     755        # was passed an undeclared keyword argument), we don't
     756        # have a _child_created attribute at all.
     757        if not getattr(self, '_child_created', False):
    665758            # We didn't get to successfully create a child process.
    666759            return
    667760        # In case the child hasn't been waited on, check if it's done.
    668         self._internal_poll(_deadstate=sys.maxint)
     761        self._internal_poll(_deadstate=_maxint)
    669762        if self.returncode is None and _active is not None:
    670763            # Child is still running, keep us alive until we can wait on it.
     
    688781            if self.stdin:
    689782                if input:
    690                     self.stdin.write(input)
     783                    try:
     784                        self.stdin.write(input)
     785                    except IOError as e:
     786                        if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
     787                            raise
    691788                self.stdin.close()
    692789            elif self.stdout:
    693                 stdout = self.stdout.read()
     790                stdout = _eintr_retry_call(self.stdout.read)
    694791                self.stdout.close()
    695792            elif self.stderr:
    696                 stderr = self.stderr.read()
     793                stderr = _eintr_retry_call(self.stderr.read)
    697794                self.stderr.close()
    698795            self.wait()
     
    711808        #
    712809        def _get_handles(self, stdin, stdout, stderr):
    713             """Construct and return tupel with IO objects:
     810            """Construct and return tuple with IO objects:
    714811            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
    715812            """
     813            to_close = set()
    716814            if stdin is None and stdout is None and stderr is None:
    717                 return (None, None, None, None, None, None)
     815                return (None, None, None, None, None, None), to_close
    718816
    719817            p2cread, p2cwrite = None, None
     
    722820
    723821            if stdin is None:
    724                 p2cread = GetStdHandle(STD_INPUT_HANDLE)
     822                p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
    725823                if p2cread is None:
    726                     p2cread, _ = CreatePipe(None, 0)
     824                    p2cread, _ = _subprocess.CreatePipe(None, 0)
    727825            elif stdin == PIPE:
    728                 p2cread, p2cwrite = CreatePipe(None, 0)
     826                p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
    729827            elif isinstance(stdin, int):
    730828                p2cread = msvcrt.get_osfhandle(stdin)
     
    733831                p2cread = msvcrt.get_osfhandle(stdin.fileno())
    734832            p2cread = self._make_inheritable(p2cread)
     833            # We just duplicated the handle, it has to be closed at the end
     834            to_close.add(p2cread)
     835            if stdin == PIPE:
     836                to_close.add(p2cwrite)
    735837
    736838            if stdout is None:
    737                 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
     839                c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
    738840                if c2pwrite is None:
    739                     _, c2pwrite = CreatePipe(None, 0)
     841                    _, c2pwrite = _subprocess.CreatePipe(None, 0)
    740842            elif stdout == PIPE:
    741                 c2pread, c2pwrite = CreatePipe(None, 0)
     843                c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
    742844            elif isinstance(stdout, int):
    743845                c2pwrite = msvcrt.get_osfhandle(stdout)
     
    746848                c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
    747849            c2pwrite = self._make_inheritable(c2pwrite)
     850            # We just duplicated the handle, it has to be closed at the end
     851            to_close.add(c2pwrite)
     852            if stdout == PIPE:
     853                to_close.add(c2pread)
    748854
    749855            if stderr is None:
    750                 errwrite = GetStdHandle(STD_ERROR_HANDLE)
     856                errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
    751857                if errwrite is None:
    752                     _, errwrite = CreatePipe(None, 0)
     858                    _, errwrite = _subprocess.CreatePipe(None, 0)
    753859            elif stderr == PIPE:
    754                 errread, errwrite = CreatePipe(None, 0)
     860                errread, errwrite = _subprocess.CreatePipe(None, 0)
    755861            elif stderr == STDOUT:
    756862                errwrite = c2pwrite
     
    761867                errwrite = msvcrt.get_osfhandle(stderr.fileno())
    762868            errwrite = self._make_inheritable(errwrite)
     869            # We just duplicated the handle, it has to be closed at the end
     870            to_close.add(errwrite)
     871            if stderr == PIPE:
     872                to_close.add(errread)
    763873
    764874            return (p2cread, p2cwrite,
    765875                    c2pread, c2pwrite,
    766                     errread, errwrite)
     876                    errread, errwrite), to_close
    767877
    768878
    769879        def _make_inheritable(self, handle):
    770880            """Return a duplicate of handle, which is inheritable"""
    771             return DuplicateHandle(GetCurrentProcess(), handle,
    772                                    GetCurrentProcess(), 0, 1,
    773                                    DUPLICATE_SAME_ACCESS)
     881            return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
     882                                handle, _subprocess.GetCurrentProcess(), 0, 1,
     883                                _subprocess.DUPLICATE_SAME_ACCESS)
    774884
    775885
    776886        def _find_w9xpopen(self):
    777887            """Find and return absolut path to w9xpopen.exe"""
    778             w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
     888            w9xpopen = os.path.join(
     889                            os.path.dirname(_subprocess.GetModuleFileName(0)),
    779890                                    "w9xpopen.exe")
    780891            if not os.path.exists(w9xpopen):
     
    792903        def _execute_child(self, args, executable, preexec_fn, close_fds,
    793904                           cwd, env, universal_newlines,
    794                            startupinfo, creationflags, shell,
     905                           startupinfo, creationflags, shell, to_close,
    795906                           p2cread, p2cwrite,
    796907                           c2pread, c2pwrite,
     
    805916                startupinfo = STARTUPINFO()
    806917            if None not in (p2cread, c2pwrite, errwrite):
    807                 startupinfo.dwFlags |= STARTF_USESTDHANDLES
     918                startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
    808919                startupinfo.hStdInput = p2cread
    809920                startupinfo.hStdOutput = c2pwrite
     
    811922
    812923            if shell:
    813                 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
    814                 startupinfo.wShowWindow = SW_HIDE
     924                startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
     925                startupinfo.wShowWindow = _subprocess.SW_HIDE
    815926                comspec = os.environ.get("COMSPEC", "cmd.exe")
    816                 args = comspec + " /c " + args
    817                 if (GetVersion() >= 0x80000000L or
     927                args = '{} /c "{}"'.format (comspec, args)
     928                if (_subprocess.GetVersion() >= 0x80000000 or
    818929                        os.path.basename(comspec).lower() == "command.com"):
    819930                    # Win9x, or using command.com on NT. We need to
     
    829940                    # stability of your system.  Cost is Ctrl+C wont
    830941                    # kill children.
    831                     creationflags |= CREATE_NEW_CONSOLE
     942                    creationflags |= _subprocess.CREATE_NEW_CONSOLE
     943
     944            def _close_in_parent(fd):
     945                fd.Close()
     946                to_close.remove(fd)
    832947
    833948            # Start the process
    834949            try:
    835                 hp, ht, pid, tid = CreateProcess(executable, args,
     950                hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
    836951                                         # no special security
    837952                                         None, None,
     
    844959                # Translate pywintypes.error to WindowsError, which is
    845960                # a subclass of OSError.  FIXME: We should really
    846                 # translate errno using _sys_errlist (or simliar), but
     961                # translate errno using _sys_errlist (or similar), but
    847962                # how can this be done from Python?
    848963                raise WindowsError(*e.args)
     964            finally:
     965                # Child is launched. Close the parent's copy of those pipe
     966                # handles that only the child should have open.  You need
     967                # to make sure that no handles to the write end of the
     968                # output pipe are maintained in this process or else the
     969                # pipe will not close when the child process exits and the
     970                # ReadFile will hang.
     971                if p2cread is not None:
     972                    _close_in_parent(p2cread)
     973                if c2pwrite is not None:
     974                    _close_in_parent(c2pwrite)
     975                if errwrite is not None:
     976                    _close_in_parent(errwrite)
    849977
    850978            # Retain the process handle, but close the thread handle
     
    854982            ht.Close()
    855983
    856             # Child is launched. Close the parent's copy of those pipe
    857             # handles that only the child should have open.  You need
    858             # to make sure that no handles to the write end of the
    859             # output pipe are maintained in this process or else the
    860             # pipe will not close when the child process exits and the
    861             # ReadFile will hang.
    862             if p2cread is not None:
    863                 p2cread.Close()
    864             if c2pwrite is not None:
    865                 c2pwrite.Close()
    866             if errwrite is not None:
    867                 errwrite.Close()
    868 
    869 
    870         def _internal_poll(self, _deadstate=None):
     984        def _internal_poll(self, _deadstate=None,
     985                _WaitForSingleObject=_subprocess.WaitForSingleObject,
     986                _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
     987                _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
    871988            """Check if child process has terminated.  Returns returncode
    872             attribute."""
     989            attribute.
     990
     991            This method is called by __del__, so it can only refer to objects
     992            in its local scope.
     993
     994            """
    873995            if self.returncode is None:
    874                 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
    875                     self.returncode = GetExitCodeProcess(self._handle)
     996                if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
     997                    self.returncode = _GetExitCodeProcess(self._handle)
    876998            return self.returncode
    877999
     
    8811003            attribute."""
    8821004            if self.returncode is None:
    883                 obj = WaitForSingleObject(self._handle, INFINITE)
    884                 self.returncode = GetExitCodeProcess(self._handle)
     1005                _subprocess.WaitForSingleObject(self._handle,
     1006                                                _subprocess.INFINITE)
     1007                self.returncode = _subprocess.GetExitCodeProcess(self._handle)
    8851008            return self.returncode
    8861009
     
    9091032            if self.stdin:
    9101033                if input is not None:
    911                     self.stdin.write(input)
     1034                    try:
     1035                        self.stdin.write(input)
     1036                    except IOError as e:
     1037                        if e.errno != errno.EPIPE:
     1038                            raise
    9121039                self.stdin.close()
    9131040
     
    9411068            if sig == signal.SIGTERM:
    9421069                self.terminate()
     1070            elif sig == signal.CTRL_C_EVENT:
     1071                os.kill(self.pid, signal.CTRL_C_EVENT)
     1072            elif sig == signal.CTRL_BREAK_EVENT:
     1073                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
    9431074            else:
    944                 raise ValueError("Only SIGTERM is supported on Windows")
     1075                raise ValueError("Unsupported signal: {}".format(sig))
    9451076
    9461077        def terminate(self):
    9471078            """Terminates the process
    9481079            """
    949             TerminateProcess(self._handle, 1)
     1080            try:
     1081                _subprocess.TerminateProcess(self._handle, 1)
     1082            except OSError as e:
     1083                # ERROR_ACCESS_DENIED (winerror 5) is received when the
     1084                # process already died.
     1085                if e.winerror != 5:
     1086                    raise
     1087                rc = _subprocess.GetExitCodeProcess(self._handle)
     1088                if rc == _subprocess.STILL_ACTIVE:
     1089                    raise
     1090                self.returncode = rc
    9501091
    9511092        kill = terminate
     
    9561097        #
    9571098        def _get_handles(self, stdin, stdout, stderr):
    958             """Construct and return tupel with IO objects:
     1099            """Construct and return tuple with IO objects:
    9591100            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
    9601101            """
     1102            to_close = set()
    9611103            p2cread, p2cwrite = None, None
    9621104            c2pread, c2pwrite = None, None
     
    9661108                pass
    9671109            elif stdin == PIPE:
    968                 p2cread, p2cwrite = os.pipe()
     1110                p2cread, p2cwrite = self.pipe_cloexec()
     1111                to_close.update((p2cread, p2cwrite))
    9691112            elif isinstance(stdin, int):
    9701113                p2cread = stdin
     
    9761119                pass
    9771120            elif stdout == PIPE:
    978                 c2pread, c2pwrite = os.pipe()
     1121                c2pread, c2pwrite = self.pipe_cloexec()
     1122                to_close.update((c2pread, c2pwrite))
    9791123            elif isinstance(stdout, int):
    9801124                c2pwrite = stdout
     
    9861130                pass
    9871131            elif stderr == PIPE:
    988                 errread, errwrite = os.pipe()
     1132                errread, errwrite = self.pipe_cloexec()
     1133                to_close.update((errread, errwrite))
    9891134            elif stderr == STDOUT:
    9901135                errwrite = c2pwrite
     
    9971142            return (p2cread, p2cwrite,
    9981143                    c2pread, c2pwrite,
    999                     errread, errwrite)
    1000 
    1001 
    1002         def _set_cloexec_flag(self, fd):
     1144                    errread, errwrite), to_close
     1145
     1146
     1147        def _set_cloexec_flag(self, fd, cloexec=True):
    10031148            try:
    10041149                cloexec_flag = fcntl.FD_CLOEXEC
     
    10071152
    10081153            old = fcntl.fcntl(fd, fcntl.F_GETFD)
    1009             fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
     1154            if cloexec:
     1155                fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
     1156            else:
     1157                fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
     1158
     1159
     1160        def pipe_cloexec(self):
     1161            """Create a pipe with FDs set CLOEXEC."""
     1162            # Pipes' FDs are set CLOEXEC by default because we don't want them
     1163            # to be inherited by other subprocesses: the CLOEXEC flag is removed
     1164            # from the child's FDs by _dup2(), between fork() and exec().
     1165            # This is not atomic: we would need the pipe2() syscall for that.
     1166            r, w = os.pipe()
     1167            self._set_cloexec_flag(r)
     1168            self._set_cloexec_flag(w)
     1169            return r, w
    10101170
    10111171
    10121172        def _close_fds(self, but):
    1013             os.closerange(3, but)
    1014             os.closerange(but + 1, MAXFD)
     1173            if hasattr(os, 'closerange'):
     1174                os.closerange(3, but)
     1175                os.closerange(but + 1, MAXFD)
     1176            else:
     1177                for i in xrange(3, MAXFD):
     1178                    if i == but:
     1179                        continue
     1180                    try:
     1181                        os.close(i)
     1182                    except:
     1183                        pass
    10151184
    10161185
    10171186        def _execute_child(self, args, executable, preexec_fn, close_fds,
    10181187                           cwd, env, universal_newlines,
    1019                            startupinfo, creationflags, shell,
     1188                           startupinfo, creationflags, shell, to_close,
    10201189                           p2cread, p2cwrite,
    10211190                           c2pread, c2pwrite,
     
    10301199            if shell:
    10311200                args = ["/bin/sh", "-c"] + args
     1201                if executable:
     1202                    args[0] = executable
    10321203
    10331204            if executable is None:
    10341205                executable = args[0]
     1206
     1207            def _close_in_parent(fd):
     1208                os.close(fd)
     1209                to_close.remove(fd)
    10351210
    10361211            # For transferring possible exec failure from child to parent
    10371212            # The first char specifies the exception type: 0 means
    10381213            # OSError, 1 means some other error.
    1039             errpipe_read, errpipe_write = os.pipe()
     1214            errpipe_read, errpipe_write = self.pipe_cloexec()
    10401215            try:
    10411216                try:
    1042                     self._set_cloexec_flag(errpipe_write)
    1043 
    10441217                    gc_was_enabled = gc.isenabled()
    10451218                    # Disable gc to avoid bug where gc -> file_dealloc ->
     
    10651238                            os.close(errpipe_read)
    10661239
     1240                            # When duping fds, if there arises a situation
     1241                            # where one of the fds is either 0, 1 or 2, it
     1242                            # is possible that it is overwritten (#12607).
     1243                            if c2pwrite == 0:
     1244                                c2pwrite = os.dup(c2pwrite)
     1245                            if errwrite == 0 or errwrite == 1:
     1246                                errwrite = os.dup(errwrite)
     1247
    10671248                            # Dup fds for child
    1068                             if p2cread is not None:
    1069                                 os.dup2(p2cread, 0)
    1070                             if c2pwrite is not None:
    1071                                 os.dup2(c2pwrite, 1)
    1072                             if errwrite is not None:
    1073                                 os.dup2(errwrite, 2)
    1074 
    1075                             # Close pipe fds.  Make sure we don't close the same
    1076                             # fd more than once, or standard fds.
    1077                             if p2cread is not None and p2cread not in (0,):
    1078                                 os.close(p2cread)
    1079                             if c2pwrite is not None and c2pwrite not in (p2cread, 1):
    1080                                 os.close(c2pwrite)
    1081                             if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
    1082                                 os.close(errwrite)
    1083 
    1084                             # Close all other fds, if asked for
     1249                            def _dup2(a, b):
     1250                                # dup2() removes the CLOEXEC flag but
     1251                                # we must do it ourselves if dup2()
     1252                                # would be a no-op (issue #10806).
     1253                                if a == b:
     1254                                    self._set_cloexec_flag(a, False)
     1255                                elif a is not None:
     1256                                    os.dup2(a, b)
     1257                            _dup2(p2cread, 0)
     1258                            _dup2(c2pwrite, 1)
     1259                            _dup2(errwrite, 2)
     1260
     1261                            # Close pipe fds.  Make sure we don't close the
     1262                            # same fd more than once, or standard fds.
     1263                            closed = { None }
     1264                            for fd in [p2cread, c2pwrite, errwrite]:
     1265                                if fd not in closed and fd > 2:
     1266                                    os.close(fd)
     1267                                    closed.add(fd)
     1268
     1269                            if cwd is not None:
     1270                                os.chdir(cwd)
     1271
     1272                            if preexec_fn:
     1273                                preexec_fn()
     1274
     1275                            # Close all other fds, if asked for - after
     1276                            # preexec_fn(), which may open FDs.
    10851277                            if close_fds:
    10861278                                self._close_fds(but=errpipe_write)
    1087 
    1088                             if cwd is not None:
    1089                                 os.chdir(cwd)
    1090 
    1091                             if preexec_fn:
    1092                                 preexec_fn()
    10931279
    10941280                            if env is None:
     
    11171303                    os.close(errpipe_write)
    11181304
    1119                 if p2cread is not None and p2cwrite is not None:
    1120                     os.close(p2cread)
    1121                 if c2pwrite is not None and c2pread is not None:
    1122                     os.close(c2pwrite)
    1123                 if errwrite is not None and errread is not None:
    1124                     os.close(errwrite)
    1125 
    11261305                # Wait for exec to fail or succeed; possibly raising exception
    11271306                # Exception limited to 1M
    11281307                data = _eintr_retry_call(os.read, errpipe_read, 1048576)
    11291308            finally:
     1309                if p2cread is not None and p2cwrite is not None:
     1310                    _close_in_parent(p2cread)
     1311                if c2pwrite is not None and c2pread is not None:
     1312                    _close_in_parent(c2pwrite)
     1313                if errwrite is not None and errread is not None:
     1314                    _close_in_parent(errwrite)
     1315
    11301316                # be sure the FD is closed no matter what
    11311317                os.close(errpipe_read)
    11321318
    11331319            if data != "":
    1134                 _eintr_retry_call(os.waitpid, self.pid, 0)
     1320                try:
     1321                    _eintr_retry_call(os.waitpid, self.pid, 0)
     1322                except OSError as e:
     1323                    if e.errno != errno.ECHILD:
     1324                        raise
    11351325                child_exception = pickle.loads(data)
    1136                 for fd in (p2cwrite, c2pread, errread):
    1137                     if fd is not None:
    1138                         os.close(fd)
    11391326                raise child_exception
    11401327
    11411328
    1142         def _handle_exitstatus(self, sts):
    1143             if os.WIFSIGNALED(sts):
    1144                 self.returncode = -os.WTERMSIG(sts)
    1145             elif os.WIFEXITED(sts):
    1146                 self.returncode = os.WEXITSTATUS(sts)
     1329        def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
     1330                _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
     1331                _WEXITSTATUS=os.WEXITSTATUS):
     1332            # This method is called (indirectly) by __del__, so it cannot
     1333            # refer to anything outside of its local scope."""
     1334            if _WIFSIGNALED(sts):
     1335                self.returncode = -_WTERMSIG(sts)
     1336            elif _WIFEXITED(sts):
     1337                self.returncode = _WEXITSTATUS(sts)
    11471338            else:
    11481339                # Should never happen
     
    11501341
    11511342
    1152         def _internal_poll(self, _deadstate=None):
     1343        def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
     1344                _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
    11531345            """Check if child process has terminated.  Returns returncode
    1154             attribute."""
     1346            attribute.
     1347
     1348            This method is called by __del__, so it cannot reference anything
     1349            outside of the local scope (nor can any methods it calls).
     1350
     1351            """
    11551352            if self.returncode is None:
    11561353                try:
    1157                     pid, sts = os.waitpid(self.pid, os.WNOHANG)
     1354                    pid, sts = _waitpid(self.pid, _WNOHANG)
    11581355                    if pid == self.pid:
    11591356                        self._handle_exitstatus(sts)
    1160                 except os.error:
     1357                except _os_error as e:
    11611358                    if _deadstate is not None:
    11621359                        self.returncode = _deadstate
     1360                    if e.errno == _ECHILD:
     1361                        # This happens if SIGCLD is set to be ignored or
     1362                        # waiting for child processes has otherwise been
     1363                        # disabled for our process.  This child is dead, we
     1364                        # can't get the status.
     1365                        # http://bugs.python.org/issue15756
     1366                        self.returncode = 0
    11631367            return self.returncode
    11641368
     
    11671371            """Wait for child process to terminate.  Returns returncode
    11681372            attribute."""
    1169             if self.returncode is None:
    1170                 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
    1171                 self._handle_exitstatus(sts)
     1373            while self.returncode is None:
     1374                try:
     1375                    pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
     1376                except OSError as e:
     1377                    if e.errno != errno.ECHILD:
     1378                        raise
     1379                    # This happens if SIGCLD is set to be ignored or waiting
     1380                    # for child processes has otherwise been disabled for our
     1381                    # process.  This child is dead, we can't get the status.
     1382                    pid = self.pid
     1383                    sts = 0
     1384                # Check the pid and loop as waitpid has been known to return
     1385                # 0 even without WNOHANG in odd situations.  issue14396.
     1386                if pid == self.pid:
     1387                    self._handle_exitstatus(sts)
    11721388            return self.returncode
    11731389
    11741390
    11751391        def _communicate(self, input):
    1176             read_set = []
    1177             write_set = []
    1178             stdout = None # Return
    1179             stderr = None # Return
    1180 
    11811392            if self.stdin:
    11821393                # Flush stdio buffer.  This might block, if the user has
    11831394                # been writing to .stdin in an uncontrolled fashion.
    11841395                self.stdin.flush()
    1185                 if input:
    1186                     write_set.append(self.stdin)
    1187                 else:
     1396                if not input:
    11881397                    self.stdin.close()
    1189             if self.stdout:
    1190                 read_set.append(self.stdout)
    1191                 stdout = []
    1192             if self.stderr:
    1193                 read_set.append(self.stderr)
    1194                 stderr = []
    1195 
    1196             input_offset = 0
    1197             while read_set or write_set:
    1198                 try:
    1199                     rlist, wlist, xlist = select.select(read_set, write_set, [])
    1200                 except select.error, e:
    1201                     if e.args[0] == errno.EINTR:
    1202                         continue
    1203                     raise
    1204 
    1205                 if self.stdin in wlist:
    1206                     # When select has indicated that the file is writable,
    1207                     # we can write up to PIPE_BUF bytes without risk
    1208                     # blocking.  POSIX defines PIPE_BUF >= 512
    1209                     chunk = input[input_offset : input_offset + 512]
    1210                     bytes_written = os.write(self.stdin.fileno(), chunk)
    1211                     input_offset += bytes_written
    1212                     if input_offset >= len(input):
    1213                         self.stdin.close()
    1214                         write_set.remove(self.stdin)
    1215 
    1216                 if self.stdout in rlist:
    1217                     data = os.read(self.stdout.fileno(), 1024)
    1218                     if data == "":
    1219                         self.stdout.close()
    1220                         read_set.remove(self.stdout)
    1221                     stdout.append(data)
    1222 
    1223                 if self.stderr in rlist:
    1224                     data = os.read(self.stderr.fileno(), 1024)
    1225                     if data == "":
    1226                         self.stderr.close()
    1227                         read_set.remove(self.stderr)
    1228                     stderr.append(data)
     1398
     1399            if _has_poll:
     1400                stdout, stderr = self._communicate_with_poll(input)
     1401            else:
     1402                stdout, stderr = self._communicate_with_select(input)
    12291403
    12301404            # All data exchanged.  Translate lists into strings.
     
    12461420            self.wait()
    12471421            return (stdout, stderr)
     1422
     1423
     1424        def _communicate_with_poll(self, input):
     1425            stdout = None # Return
     1426            stderr = None # Return
     1427            fd2file = {}
     1428            fd2output = {}
     1429
     1430            poller = select.poll()
     1431            def register_and_append(file_obj, eventmask):
     1432                poller.register(file_obj.fileno(), eventmask)
     1433                fd2file[file_obj.fileno()] = file_obj
     1434
     1435            def close_unregister_and_remove(fd):
     1436                poller.unregister(fd)
     1437                fd2file[fd].close()
     1438                fd2file.pop(fd)
     1439
     1440            if self.stdin and input:
     1441                register_and_append(self.stdin, select.POLLOUT)
     1442
     1443            select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
     1444            if self.stdout:
     1445                register_and_append(self.stdout, select_POLLIN_POLLPRI)
     1446                fd2output[self.stdout.fileno()] = stdout = []
     1447            if self.stderr:
     1448                register_and_append(self.stderr, select_POLLIN_POLLPRI)
     1449                fd2output[self.stderr.fileno()] = stderr = []
     1450
     1451            input_offset = 0
     1452            while fd2file:
     1453                try:
     1454                    ready = poller.poll()
     1455                except select.error, e:
     1456                    if e.args[0] == errno.EINTR:
     1457                        continue
     1458                    raise
     1459
     1460                for fd, mode in ready:
     1461                    if mode & select.POLLOUT:
     1462                        chunk = input[input_offset : input_offset + _PIPE_BUF]
     1463                        try:
     1464                            input_offset += os.write(fd, chunk)
     1465                        except OSError as e:
     1466                            if e.errno == errno.EPIPE:
     1467                                close_unregister_and_remove(fd)
     1468                            else:
     1469                                raise
     1470                        else:
     1471                            if input_offset >= len(input):
     1472                                close_unregister_and_remove(fd)
     1473                    elif mode & select_POLLIN_POLLPRI:
     1474                        data = os.read(fd, 4096)
     1475                        if not data:
     1476                            close_unregister_and_remove(fd)
     1477                        fd2output[fd].append(data)
     1478                    else:
     1479                        # Ignore hang up or errors.
     1480                        close_unregister_and_remove(fd)
     1481
     1482            return (stdout, stderr)
     1483
     1484
     1485        def _communicate_with_select(self, input):
     1486            read_set = []
     1487            write_set = []
     1488            stdout = None # Return
     1489            stderr = None # Return
     1490
     1491            if self.stdin and input:
     1492                write_set.append(self.stdin)
     1493            if self.stdout:
     1494                read_set.append(self.stdout)
     1495                stdout = []
     1496            if self.stderr:
     1497                read_set.append(self.stderr)
     1498                stderr = []
     1499
     1500            input_offset = 0
     1501            while read_set or write_set:
     1502                try:
     1503                    rlist, wlist, xlist = select.select(read_set, write_set, [])
     1504                except select.error, e:
     1505                    if e.args[0] == errno.EINTR:
     1506                        continue
     1507                    raise
     1508
     1509                if self.stdin in wlist:
     1510                    chunk = input[input_offset : input_offset + _PIPE_BUF]
     1511                    try:
     1512                        bytes_written = os.write(self.stdin.fileno(), chunk)
     1513                    except OSError as e:
     1514                        if e.errno == errno.EPIPE:
     1515                            self.stdin.close()
     1516                            write_set.remove(self.stdin)
     1517                        else:
     1518                            raise
     1519                    else:
     1520                        input_offset += bytes_written
     1521                        if input_offset >= len(input):
     1522                            self.stdin.close()
     1523                            write_set.remove(self.stdin)
     1524
     1525                if self.stdout in rlist:
     1526                    data = os.read(self.stdout.fileno(), 1024)
     1527                    if data == "":
     1528                        self.stdout.close()
     1529                        read_set.remove(self.stdout)
     1530                    stdout.append(data)
     1531
     1532                if self.stderr in rlist:
     1533                    data = os.read(self.stderr.fileno(), 1024)
     1534                    if data == "":
     1535                        self.stderr.close()
     1536                        read_set.remove(self.stderr)
     1537                    stderr.append(data)
     1538
     1539            return (stdout, stderr)
     1540
    12481541
    12491542        def send_signal(self, sig):
Note: See TracChangeset for help on using the changeset viewer.