Changeset 388 for python/vendor/current/Lib/subprocess.py
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Lib/subprocess.py
r2 r388 2 2 # 3 3 # For more information about this module, see PEP 324. 4 #5 # This module should remain compatible with Python 2.2, see PEP 291.6 4 # 7 5 # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> … … 108 106 109 107 110 This module also defines twoshortcut functions:108 This module also defines some shortcut functions: 111 109 112 110 call(*popenargs, **kwargs): … … 127 125 128 126 check_call(["ls", "-l"]) 127 128 check_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 129 139 130 140 Exceptions … … 134 144 the exception object will have one extra attribute called 135 145 'child_traceback', which is a string containing traceback information 136 from the child s point of view.146 from the child's point of view. 137 147 138 148 The most common exception raised is OSError. This occurs, for … … 142 152 A ValueError will be raised if Popen is called with invalid arguments. 143 153 144 check_call() will raise CalledProcessError, if the called process145 returns a non-zero return code.154 check_call() and check_output() will raise CalledProcessError, if the 155 called process returns a non-zero return code. 146 156 147 157 … … 338 348 ... 339 349 rc = pipe.close() 340 if rc !=None and rc % 256:350 if rc is not None and rc % 256: 341 351 print "There were some errors" 342 352 ==> … … 385 395 import gc 386 396 import signal 397 import errno 387 398 388 399 # Exception classes used by this module. 389 400 class 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): 394 407 self.returncode = returncode 395 408 self.cmd = cmd 409 self.output = output 396 410 def __str__(self): 397 411 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) … … 401 415 import threading 402 416 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 426 426 else: 427 427 import select 428 import errno428 _has_poll = hasattr(select, 'poll') 429 429 import fcntl 430 430 import pickle 431 431 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 441 if 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"]) 434 451 try: 435 452 MAXFD = os.sysconf("SC_OPEN_MAX") … … 437 454 MAXFD = 256 438 455 439 # True/False does not exist on 2.2.0440 #try:441 # False442 #except NameError:443 # False = 0444 # True = 1445 446 456 _active = [] 447 457 448 458 def _cleanup(): 449 459 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: 451 462 try: 452 463 _active.remove(inst) … … 464 475 try: 465 476 return func(*args) 466 except OSError,e:477 except (OSError, IOError) as e: 467 478 if e.errno == errno.EINTR: 468 479 continue 469 480 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 487 def _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 470 512 471 513 … … 492 534 """ 493 535 retcode = call(*popenargs, **kwargs) 494 cmd = kwargs.get("args")495 if cmd is None:496 cmd = popenargs[0]497 536 if retcode: 537 cmd = kwargs.get("args") 538 if cmd is None: 539 cmd = popenargs[0] 498 540 raise CalledProcessError(retcode, cmd) 499 return retcode 541 return 0 542 543 544 def 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 500 575 501 576 … … 510 585 2) A string surrounded by double quotation marks is 511 586 interpreted as a single argument, regardless of white space 512 or pipe characters contained within. A quoted string can be513 embedded in anargument.587 contained within. A quoted string can be embedded in an 588 argument. 514 589 515 590 3) A double quotation mark preceded by a backslash is … … 539 614 result.append(' ') 540 615 541 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) ornot arg616 needquote = (" " in arg) or ("\t" in arg) or not arg 542 617 if needquote: 543 618 result.append('"') … … 624 699 (p2cread, p2cwrite, 625 700 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 634 724 635 725 if mswindows: … … 661 751 662 752 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): 665 758 # We didn't get to successfully create a child process. 666 759 return 667 760 # 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) 669 762 if self.returncode is None and _active is not None: 670 763 # Child is still running, keep us alive until we can wait on it. … … 688 781 if self.stdin: 689 782 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 691 788 self.stdin.close() 692 789 elif self.stdout: 693 stdout = self.stdout.read()790 stdout = _eintr_retry_call(self.stdout.read) 694 791 self.stdout.close() 695 792 elif self.stderr: 696 stderr = self.stderr.read()793 stderr = _eintr_retry_call(self.stderr.read) 697 794 self.stderr.close() 698 795 self.wait() … … 711 808 # 712 809 def _get_handles(self, stdin, stdout, stderr): 713 """Construct and return tup elwith IO objects:810 """Construct and return tuple with IO objects: 714 811 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite 715 812 """ 813 to_close = set() 716 814 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 718 816 719 817 p2cread, p2cwrite = None, None … … 722 820 723 821 if stdin is None: 724 p2cread = GetStdHandle(STD_INPUT_HANDLE)822 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE) 725 823 if p2cread is None: 726 p2cread, _ = CreatePipe(None, 0)824 p2cread, _ = _subprocess.CreatePipe(None, 0) 727 825 elif stdin == PIPE: 728 p2cread, p2cwrite = CreatePipe(None, 0)826 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0) 729 827 elif isinstance(stdin, int): 730 828 p2cread = msvcrt.get_osfhandle(stdin) … … 733 831 p2cread = msvcrt.get_osfhandle(stdin.fileno()) 734 832 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) 735 837 736 838 if stdout is None: 737 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)839 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE) 738 840 if c2pwrite is None: 739 _, c2pwrite = CreatePipe(None, 0)841 _, c2pwrite = _subprocess.CreatePipe(None, 0) 740 842 elif stdout == PIPE: 741 c2pread, c2pwrite = CreatePipe(None, 0)843 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0) 742 844 elif isinstance(stdout, int): 743 845 c2pwrite = msvcrt.get_osfhandle(stdout) … … 746 848 c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) 747 849 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) 748 854 749 855 if stderr is None: 750 errwrite = GetStdHandle(STD_ERROR_HANDLE)856 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE) 751 857 if errwrite is None: 752 _, errwrite = CreatePipe(None, 0)858 _, errwrite = _subprocess.CreatePipe(None, 0) 753 859 elif stderr == PIPE: 754 errread, errwrite = CreatePipe(None, 0)860 errread, errwrite = _subprocess.CreatePipe(None, 0) 755 861 elif stderr == STDOUT: 756 862 errwrite = c2pwrite … … 761 867 errwrite = msvcrt.get_osfhandle(stderr.fileno()) 762 868 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) 763 873 764 874 return (p2cread, p2cwrite, 765 875 c2pread, c2pwrite, 766 errread, errwrite) 876 errread, errwrite), to_close 767 877 768 878 769 879 def _make_inheritable(self, handle): 770 880 """Return a duplicate of handle, which is inheritable""" 771 return DuplicateHandle(GetCurrentProcess(), handle,772 773 881 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), 882 handle, _subprocess.GetCurrentProcess(), 0, 1, 883 _subprocess.DUPLICATE_SAME_ACCESS) 774 884 775 885 776 886 def _find_w9xpopen(self): 777 887 """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)), 779 890 "w9xpopen.exe") 780 891 if not os.path.exists(w9xpopen): … … 792 903 def _execute_child(self, args, executable, preexec_fn, close_fds, 793 904 cwd, env, universal_newlines, 794 startupinfo, creationflags, shell, 905 startupinfo, creationflags, shell, to_close, 795 906 p2cread, p2cwrite, 796 907 c2pread, c2pwrite, … … 805 916 startupinfo = STARTUPINFO() 806 917 if None not in (p2cread, c2pwrite, errwrite): 807 startupinfo.dwFlags |= STARTF_USESTDHANDLES918 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES 808 919 startupinfo.hStdInput = p2cread 809 920 startupinfo.hStdOutput = c2pwrite … … 811 922 812 923 if shell: 813 startupinfo.dwFlags |= STARTF_USESHOWWINDOW814 startupinfo.wShowWindow = SW_HIDE924 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW 925 startupinfo.wShowWindow = _subprocess.SW_HIDE 815 926 comspec = os.environ.get("COMSPEC", "cmd.exe") 816 args = comspec + " /c " + args817 if ( GetVersion() >= 0x80000000Lor927 args = '{} /c "{}"'.format (comspec, args) 928 if (_subprocess.GetVersion() >= 0x80000000 or 818 929 os.path.basename(comspec).lower() == "command.com"): 819 930 # Win9x, or using command.com on NT. We need to … … 829 940 # stability of your system. Cost is Ctrl+C wont 830 941 # 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) 832 947 833 948 # Start the process 834 949 try: 835 hp, ht, pid, tid = CreateProcess(executable, args,950 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args, 836 951 # no special security 837 952 None, None, … … 844 959 # Translate pywintypes.error to WindowsError, which is 845 960 # a subclass of OSError. FIXME: We should really 846 # translate errno using _sys_errlist (or sim liar), but961 # translate errno using _sys_errlist (or similar), but 847 962 # how can this be done from Python? 848 963 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) 849 977 850 978 # Retain the process handle, but close the thread handle … … 854 982 ht.Close() 855 983 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): 871 988 """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 """ 873 995 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) 876 998 return self.returncode 877 999 … … 881 1003 attribute.""" 882 1004 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) 885 1008 return self.returncode 886 1009 … … 909 1032 if self.stdin: 910 1033 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 912 1039 self.stdin.close() 913 1040 … … 941 1068 if sig == signal.SIGTERM: 942 1069 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) 943 1074 else: 944 raise ValueError(" Only SIGTERM is supported on Windows")1075 raise ValueError("Unsupported signal: {}".format(sig)) 945 1076 946 1077 def terminate(self): 947 1078 """Terminates the process 948 1079 """ 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 950 1091 951 1092 kill = terminate … … 956 1097 # 957 1098 def _get_handles(self, stdin, stdout, stderr): 958 """Construct and return tup elwith IO objects:1099 """Construct and return tuple with IO objects: 959 1100 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite 960 1101 """ 1102 to_close = set() 961 1103 p2cread, p2cwrite = None, None 962 1104 c2pread, c2pwrite = None, None … … 966 1108 pass 967 1109 elif stdin == PIPE: 968 p2cread, p2cwrite = os.pipe() 1110 p2cread, p2cwrite = self.pipe_cloexec() 1111 to_close.update((p2cread, p2cwrite)) 969 1112 elif isinstance(stdin, int): 970 1113 p2cread = stdin … … 976 1119 pass 977 1120 elif stdout == PIPE: 978 c2pread, c2pwrite = os.pipe() 1121 c2pread, c2pwrite = self.pipe_cloexec() 1122 to_close.update((c2pread, c2pwrite)) 979 1123 elif isinstance(stdout, int): 980 1124 c2pwrite = stdout … … 986 1130 pass 987 1131 elif stderr == PIPE: 988 errread, errwrite = os.pipe() 1132 errread, errwrite = self.pipe_cloexec() 1133 to_close.update((errread, errwrite)) 989 1134 elif stderr == STDOUT: 990 1135 errwrite = c2pwrite … … 997 1142 return (p2cread, p2cwrite, 998 1143 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): 1003 1148 try: 1004 1149 cloexec_flag = fcntl.FD_CLOEXEC … … 1007 1152 1008 1153 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 1010 1170 1011 1171 1012 1172 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 1015 1184 1016 1185 1017 1186 def _execute_child(self, args, executable, preexec_fn, close_fds, 1018 1187 cwd, env, universal_newlines, 1019 startupinfo, creationflags, shell, 1188 startupinfo, creationflags, shell, to_close, 1020 1189 p2cread, p2cwrite, 1021 1190 c2pread, c2pwrite, … … 1030 1199 if shell: 1031 1200 args = ["/bin/sh", "-c"] + args 1201 if executable: 1202 args[0] = executable 1032 1203 1033 1204 if executable is None: 1034 1205 executable = args[0] 1206 1207 def _close_in_parent(fd): 1208 os.close(fd) 1209 to_close.remove(fd) 1035 1210 1036 1211 # For transferring possible exec failure from child to parent 1037 1212 # The first char specifies the exception type: 0 means 1038 1213 # OSError, 1 means some other error. 1039 errpipe_read, errpipe_write = os.pipe()1214 errpipe_read, errpipe_write = self.pipe_cloexec() 1040 1215 try: 1041 1216 try: 1042 self._set_cloexec_flag(errpipe_write)1043 1044 1217 gc_was_enabled = gc.isenabled() 1045 1218 # Disable gc to avoid bug where gc -> file_dealloc -> … … 1065 1238 os.close(errpipe_read) 1066 1239 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 1067 1248 # 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. 1085 1277 if close_fds: 1086 1278 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()1093 1279 1094 1280 if env is None: … … 1117 1303 os.close(errpipe_write) 1118 1304 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 1126 1305 # Wait for exec to fail or succeed; possibly raising exception 1127 1306 # Exception limited to 1M 1128 1307 data = _eintr_retry_call(os.read, errpipe_read, 1048576) 1129 1308 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 1130 1316 # be sure the FD is closed no matter what 1131 1317 os.close(errpipe_read) 1132 1318 1133 1319 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 1135 1325 child_exception = pickle.loads(data) 1136 for fd in (p2cwrite, c2pread, errread):1137 if fd is not None:1138 os.close(fd)1139 1326 raise child_exception 1140 1327 1141 1328 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) 1147 1338 else: 1148 1339 # Should never happen … … 1150 1341 1151 1342 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): 1153 1345 """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 """ 1155 1352 if self.returncode is None: 1156 1353 try: 1157 pid, sts = os.waitpid(self.pid, os.WNOHANG)1354 pid, sts = _waitpid(self.pid, _WNOHANG) 1158 1355 if pid == self.pid: 1159 1356 self._handle_exitstatus(sts) 1160 except os.error:1357 except _os_error as e: 1161 1358 if _deadstate is not None: 1162 1359 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 1163 1367 return self.returncode 1164 1368 … … 1167 1371 """Wait for child process to terminate. Returns returncode 1168 1372 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) 1172 1388 return self.returncode 1173 1389 1174 1390 1175 1391 def _communicate(self, input): 1176 read_set = []1177 write_set = []1178 stdout = None # Return1179 stderr = None # Return1180 1181 1392 if self.stdin: 1182 1393 # Flush stdio buffer. This might block, if the user has 1183 1394 # been writing to .stdin in an uncontrolled fashion. 1184 1395 self.stdin.flush() 1185 if input: 1186 write_set.append(self.stdin) 1187 else: 1396 if not input: 1188 1397 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) 1229 1403 1230 1404 # All data exchanged. Translate lists into strings. … … 1246 1420 self.wait() 1247 1421 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 1248 1541 1249 1542 def send_signal(self, sig):
Note:
See TracChangeset
for help on using the changeset viewer.