Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | # subprocess - Subprocesses with accessible I/O streams |
| 2 | # |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 3 | # For more information about this module, see PEP 324. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 4 | # |
Peter Astrand | 3a708df | 2005-09-23 17:37:29 +0000 | [diff] [blame] | 5 | # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 6 | # |
Peter Astrand | 69bf13f | 2005-02-14 08:56:32 +0000 | [diff] [blame] | 7 | # Licensed to PSF under a Contributor Agreement. |
Peter Astrand | 3a708df | 2005-09-23 17:37:29 +0000 | [diff] [blame] | 8 | # See http://www.python.org/2.4/license for licensing details. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 9 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 10 | r"""Subprocesses with accessible I/O streams |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 11 | |
Fredrik Lundh | 15aaacc | 2004-10-17 14:47:05 +0000 | [diff] [blame] | 12 | This module allows you to spawn processes, connect to their |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 13 | input/output/error pipes, and obtain their return codes. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 14 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 15 | For a complete description of this module see the Python documentation. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 16 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 17 | Main API |
| 18 | ======== |
| 19 | run(...): Runs a command, waits for it to complete, then returns a |
| 20 | CompletedProcess instance. |
| 21 | Popen(...): A class for flexibly executing a command in a new process |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 22 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 23 | Constants |
| 24 | --------- |
| 25 | DEVNULL: Special value that indicates that os.devnull should be used |
| 26 | PIPE: Special value that indicates a pipe should be created |
| 27 | STDOUT: Special value that indicates that stderr should go to stdout |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 28 | |
| 29 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 30 | Older API |
| 31 | ========= |
| 32 | call(...): Runs a command, waits for it to complete, then returns |
| 33 | the return code. |
| 34 | check_call(...): Same as call() but raises CalledProcessError() |
| 35 | if return code is not 0 |
| 36 | check_output(...): Same as check_call() but returns the contents of |
| 37 | stdout instead of a return code |
| 38 | getoutput(...): Runs a command in the shell, waits for it to complete, |
| 39 | then returns the output |
| 40 | getstatusoutput(...): Runs a command in the shell, waits for it to complete, |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 41 | then returns a (exitcode, output) tuple |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 42 | """ |
| 43 | |
| 44 | import sys |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 45 | _mswindows = (sys.platform == "win32") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 46 | |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 47 | import io |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 48 | import os |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 49 | import time |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 50 | import signal |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 51 | import builtins |
Gregory P. Smith | d23047b | 2010-12-04 09:10:44 +0000 | [diff] [blame] | 52 | import warnings |
Ross Lagerwall | 4f61b02 | 2011-04-05 15:34:00 +0200 | [diff] [blame] | 53 | import errno |
Victor Stinner | ae58649 | 2014-09-02 23:18:25 +0200 | [diff] [blame] | 54 | from time import monotonic as _time |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 55 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 56 | # Exception classes used by this module. |
Gregory P. Smith | 54d412e | 2011-03-14 14:08:43 -0400 | [diff] [blame] | 57 | class SubprocessError(Exception): pass |
| 58 | |
| 59 | |
| 60 | class CalledProcessError(SubprocessError): |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 61 | """Raised when run() is called with check=True and the process |
| 62 | returns a non-zero exit status. |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 63 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 64 | Attributes: |
| 65 | cmd, returncode, stdout, stderr, output |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 66 | """ |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 67 | def __init__(self, returncode, cmd, output=None, stderr=None): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 68 | self.returncode = returncode |
| 69 | self.cmd = cmd |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 70 | self.output = output |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 71 | self.stderr = stderr |
| 72 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 73 | def __str__(self): |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | d6da760 | 2016-06-03 06:14:06 +0000 | [diff] [blame] | 74 | if self.returncode and self.returncode < 0: |
| 75 | try: |
| 76 | return "Command '%s' died with %r." % ( |
| 77 | self.cmd, signal.Signals(-self.returncode)) |
| 78 | except ValueError: |
| 79 | return "Command '%s' died with unknown signal %d." % ( |
| 80 | self.cmd, -self.returncode) |
| 81 | else: |
| 82 | return "Command '%s' returned non-zero exit status %d." % ( |
| 83 | self.cmd, self.returncode) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 84 | |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 85 | @property |
| 86 | def stdout(self): |
| 87 | """Alias for output attribute, to match stderr""" |
| 88 | return self.output |
| 89 | |
| 90 | @stdout.setter |
| 91 | def stdout(self, value): |
| 92 | # There's no obvious reason to set this, but allow it anyway so |
| 93 | # .stdout is a transparent alias for .output |
| 94 | self.output = value |
| 95 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 96 | |
Gregory P. Smith | 54d412e | 2011-03-14 14:08:43 -0400 | [diff] [blame] | 97 | class TimeoutExpired(SubprocessError): |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 98 | """This exception is raised when the timeout expires while waiting for a |
| 99 | child process. |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 100 | |
| 101 | Attributes: |
| 102 | cmd, output, stdout, stderr, timeout |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 103 | """ |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 104 | def __init__(self, cmd, timeout, output=None, stderr=None): |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 105 | self.cmd = cmd |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 106 | self.timeout = timeout |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 107 | self.output = output |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 108 | self.stderr = stderr |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 109 | |
| 110 | def __str__(self): |
| 111 | return ("Command '%s' timed out after %s seconds" % |
| 112 | (self.cmd, self.timeout)) |
| 113 | |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 114 | @property |
| 115 | def stdout(self): |
| 116 | return self.output |
| 117 | |
| 118 | @stdout.setter |
| 119 | def stdout(self, value): |
| 120 | # There's no obvious reason to set this, but allow it anyway so |
| 121 | # .stdout is a transparent alias for .output |
| 122 | self.output = value |
| 123 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 124 | |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 125 | if _mswindows: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 126 | import threading |
| 127 | import msvcrt |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 128 | import _winapi |
Brian Curtin | 1ce6b58 | 2010-04-24 16:19:22 +0000 | [diff] [blame] | 129 | class STARTUPINFO: |
Subhendu Ghosh | ae160bb | 2017-02-25 20:29:05 +0530 | [diff] [blame] | 130 | def __init__(self, *, dwFlags=0, hStdInput=None, hStdOutput=None, |
| 131 | hStdError=None, wShowWindow=0): |
| 132 | self.dwFlags = dwFlags |
| 133 | self.hStdInput = hStdInput |
| 134 | self.hStdOutput = hStdOutput |
| 135 | self.hStdError = hStdError |
| 136 | self.wShowWindow = wShowWindow |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 137 | else: |
Gregory P. Smith | 59fd1bf | 2011-05-28 09:32:39 -0700 | [diff] [blame] | 138 | import _posixsubprocess |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 139 | import select |
| 140 | import selectors |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 141 | import threading |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 142 | |
Amaury Forgeot d'Arc | ace3102 | 2009-07-09 22:44:11 +0000 | [diff] [blame] | 143 | # When select or poll has indicated that the file is writable, |
| 144 | # we can write up to _PIPE_BUF bytes without risk of blocking. |
| 145 | # POSIX defines PIPE_BUF as >= 512. |
| 146 | _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) |
| 147 | |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 148 | # poll/select have the advantage of not requiring any extra file |
| 149 | # descriptor, contrarily to epoll/kqueue (also, they require a single |
| 150 | # syscall). |
| 151 | if hasattr(selectors, 'PollSelector'): |
| 152 | _PopenSelector = selectors.PollSelector |
| 153 | else: |
| 154 | _PopenSelector = selectors.SelectSelector |
| 155 | |
Amaury Forgeot d'Arc | ace3102 | 2009-07-09 22:44:11 +0000 | [diff] [blame] | 156 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 157 | __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput", |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 158 | "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL", |
| 159 | "SubprocessError", "TimeoutExpired", "CompletedProcess"] |
Gregory P. Smith | ace5586 | 2015-04-07 15:57:54 -0700 | [diff] [blame] | 160 | # NOTE: We intentionally exclude list2cmdline as it is |
| 161 | # considered an internal implementation detail. issue10838. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 162 | |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 163 | if _mswindows: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 164 | from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, |
| 165 | STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, |
| 166 | STD_ERROR_HANDLE, SW_HIDE, |
James | b5d9e08 | 2017-11-08 14:18:59 +0000 | [diff] [blame] | 167 | STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW, |
| 168 | ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, |
| 169 | HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS, |
| 170 | NORMAL_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS, |
| 171 | CREATE_NO_WINDOW, DETACHED_PROCESS, |
| 172 | CREATE_DEFAULT_ERROR_MODE, CREATE_BREAKAWAY_FROM_JOB) |
Brian Curtin | 5d9deaa | 2011-04-29 16:24:07 -0500 | [diff] [blame] | 173 | |
Brian Curtin | 08fd8d9 | 2011-04-29 16:11:30 -0500 | [diff] [blame] | 174 | __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", |
Brian Curtin | 8b8e7f4 | 2011-04-29 15:48:13 -0500 | [diff] [blame] | 175 | "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", |
| 176 | "STD_ERROR_HANDLE", "SW_HIDE", |
Martin Panter | 528619b | 2016-04-16 23:42:37 +0000 | [diff] [blame] | 177 | "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW", |
James | b5d9e08 | 2017-11-08 14:18:59 +0000 | [diff] [blame] | 178 | "STARTUPINFO", |
| 179 | "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS", |
| 180 | "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", |
| 181 | "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS", |
| 182 | "CREATE_NO_WINDOW", "DETACHED_PROCESS", |
| 183 | "CREATE_DEFAULT_ERROR_MODE", "CREATE_BREAKAWAY_FROM_JOB"]) |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 184 | |
| 185 | class Handle(int): |
| 186 | closed = False |
| 187 | |
| 188 | def Close(self, CloseHandle=_winapi.CloseHandle): |
| 189 | if not self.closed: |
| 190 | self.closed = True |
| 191 | CloseHandle(self) |
| 192 | |
| 193 | def Detach(self): |
| 194 | if not self.closed: |
| 195 | self.closed = True |
| 196 | return int(self) |
| 197 | raise ValueError("already closed") |
| 198 | |
| 199 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 200 | return "%s(%d)" % (self.__class__.__name__, int(self)) |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 201 | |
| 202 | __del__ = Close |
| 203 | __str__ = __repr__ |
| 204 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 205 | |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 206 | # This lists holds Popen instances for which the underlying process had not |
| 207 | # exited at the time its __del__ method got called: those processes are wait()ed |
| 208 | # for synchronously from _cleanup() when a new Popen object is created, to avoid |
| 209 | # zombie processes. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 210 | _active = [] |
| 211 | |
| 212 | def _cleanup(): |
| 213 | for inst in _active[:]: |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 214 | res = inst._internal_poll(_deadstate=sys.maxsize) |
Charles-François Natali | 134a8ba | 2011-08-18 18:49:39 +0200 | [diff] [blame] | 215 | if res is not None: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 216 | try: |
| 217 | _active.remove(inst) |
| 218 | except ValueError: |
| 219 | # This can happen if two threads create a new Popen instance. |
| 220 | # It's harmless that it was already removed, so ignore. |
| 221 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 222 | |
| 223 | PIPE = -1 |
| 224 | STDOUT = -2 |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 225 | DEVNULL = -3 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 226 | |
| 227 | |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 228 | # XXX This function is only used by multiprocessing and the test suite, |
| 229 | # but it's here so that it can be imported when Python is compiled without |
| 230 | # threads. |
| 231 | |
Victor Stinner | 9def284 | 2016-01-18 12:15:08 +0100 | [diff] [blame] | 232 | def _optim_args_from_interpreter_flags(): |
| 233 | """Return a list of command-line arguments reproducing the current |
| 234 | optimization settings in sys.flags.""" |
| 235 | args = [] |
| 236 | value = sys.flags.optimize |
| 237 | if value > 0: |
| 238 | args.append('-' + 'O' * value) |
| 239 | return args |
| 240 | |
| 241 | |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 242 | def _args_from_interpreter_flags(): |
| 243 | """Return a list of command-line arguments reproducing the current |
Victor Stinner | 747f48e | 2017-12-12 22:59:48 +0100 | [diff] [blame] | 244 | settings in sys.flags, sys.warnoptions and sys._xoptions.""" |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 245 | flag_opt_map = { |
| 246 | 'debug': 'd', |
| 247 | # 'inspect': 'i', |
| 248 | # 'interactive': 'i', |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 249 | 'dont_write_bytecode': 'B', |
| 250 | 'no_user_site': 's', |
| 251 | 'no_site': 'S', |
| 252 | 'ignore_environment': 'E', |
| 253 | 'verbose': 'v', |
| 254 | 'bytes_warning': 'b', |
| 255 | 'quiet': 'q', |
Victor Stinner | 9def284 | 2016-01-18 12:15:08 +0100 | [diff] [blame] | 256 | # -O is handled in _optim_args_from_interpreter_flags() |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 257 | } |
Victor Stinner | 9def284 | 2016-01-18 12:15:08 +0100 | [diff] [blame] | 258 | args = _optim_args_from_interpreter_flags() |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 259 | for flag, opt in flag_opt_map.items(): |
| 260 | v = getattr(sys.flags, flag) |
| 261 | if v > 0: |
| 262 | args.append('-' + opt * v) |
Victor Stinner | f39b674 | 2017-11-20 15:24:56 -0800 | [diff] [blame] | 263 | |
| 264 | # -W options |
Victor Stinner | 747f48e | 2017-12-12 22:59:48 +0100 | [diff] [blame] | 265 | warnopts = sys.warnoptions[:] |
| 266 | bytes_warning = sys.flags.bytes_warning |
| 267 | xoptions = getattr(sys, '_xoptions', {}) |
| 268 | dev_mode = ('dev' in xoptions) |
| 269 | |
| 270 | if bytes_warning > 1: |
| 271 | warnopts.remove("error::BytesWarning") |
| 272 | elif bytes_warning: |
| 273 | warnopts.remove("default::BytesWarning") |
| 274 | if dev_mode: |
| 275 | warnopts.remove('default') |
| 276 | for opt in warnopts: |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 277 | args.append('-W' + opt) |
Victor Stinner | f39b674 | 2017-11-20 15:24:56 -0800 | [diff] [blame] | 278 | |
| 279 | # -X options |
Victor Stinner | 747f48e | 2017-12-12 22:59:48 +0100 | [diff] [blame] | 280 | if dev_mode: |
Victor Stinner | f39b674 | 2017-11-20 15:24:56 -0800 | [diff] [blame] | 281 | args.extend(('-X', 'dev')) |
| 282 | for opt in ('faulthandler', 'tracemalloc', 'importtime', |
Victor Stinner | 91106cd | 2017-12-13 12:29:09 +0100 | [diff] [blame^] | 283 | 'showalloccount', 'showrefcount', 'utf8'): |
Victor Stinner | f39b674 | 2017-11-20 15:24:56 -0800 | [diff] [blame] | 284 | if opt in xoptions: |
| 285 | value = xoptions[opt] |
| 286 | if value is True: |
| 287 | arg = opt |
| 288 | else: |
| 289 | arg = '%s=%s' % (opt, value) |
| 290 | args.extend(('-X', arg)) |
| 291 | |
Antoine Pitrou | ebdcd85 | 2012-05-18 18:33:07 +0200 | [diff] [blame] | 292 | return args |
| 293 | |
| 294 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 295 | def call(*popenargs, timeout=None, **kwargs): |
| 296 | """Run command with arguments. Wait for command to complete or |
| 297 | timeout, then return the returncode attribute. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 298 | |
| 299 | The arguments are the same as for the Popen constructor. Example: |
| 300 | |
| 301 | retcode = call(["ls", "-l"]) |
| 302 | """ |
Victor Stinner | c15c88c | 2011-09-01 23:45:04 +0200 | [diff] [blame] | 303 | with Popen(*popenargs, **kwargs) as p: |
| 304 | try: |
| 305 | return p.wait(timeout=timeout) |
| 306 | except: |
| 307 | p.kill() |
| 308 | p.wait() |
| 309 | raise |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 310 | |
| 311 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 312 | def check_call(*popenargs, **kwargs): |
| 313 | """Run command with arguments. Wait for command to complete. If |
| 314 | the exit code was zero then return, otherwise raise |
| 315 | CalledProcessError. The CalledProcessError object will have the |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 316 | return code in the returncode attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 317 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 318 | The arguments are the same as for the call function. Example: |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 319 | |
| 320 | check_call(["ls", "-l"]) |
| 321 | """ |
| 322 | retcode = call(*popenargs, **kwargs) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 323 | if retcode: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 324 | cmd = kwargs.get("args") |
| 325 | if cmd is None: |
| 326 | cmd = popenargs[0] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 327 | raise CalledProcessError(retcode, cmd) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 328 | return 0 |
| 329 | |
| 330 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 331 | def check_output(*popenargs, timeout=None, **kwargs): |
Gregory P. Smith | 91110f5 | 2013-03-19 23:25:16 -0700 | [diff] [blame] | 332 | r"""Run command with arguments and return its output. |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 333 | |
| 334 | If the exit code was non-zero it raises a CalledProcessError. The |
| 335 | CalledProcessError object will have the return code in the returncode |
| 336 | attribute and output in the output attribute. |
| 337 | |
| 338 | The arguments are the same as for the Popen constructor. Example: |
| 339 | |
| 340 | >>> check_output(["ls", "-l", "/dev/null"]) |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 341 | b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 342 | |
| 343 | The stdout argument is not allowed as it is used internally. |
Georg Brandl | 127d470 | 2009-12-28 08:10:38 +0000 | [diff] [blame] | 344 | To capture standard error in the result, use stderr=STDOUT. |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 345 | |
| 346 | >>> check_output(["/bin/sh", "-c", |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 347 | ... "ls -l non_existent_file ; exit 0"], |
Georg Brandl | 127d470 | 2009-12-28 08:10:38 +0000 | [diff] [blame] | 348 | ... stderr=STDOUT) |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 349 | b'ls: non_existent_file: No such file or directory\n' |
Gregory P. Smith | 91110f5 | 2013-03-19 23:25:16 -0700 | [diff] [blame] | 350 | |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 351 | There is an additional optional argument, "input", allowing you to |
| 352 | pass a string to the subprocess's stdin. If you use this argument |
| 353 | you may not also use the Popen constructor's "stdin" argument, as |
| 354 | it too will be used internally. Example: |
| 355 | |
| 356 | >>> check_output(["sed", "-e", "s/foo/bar/"], |
| 357 | ... input=b"when in the course of fooman events\n") |
| 358 | b'when in the course of barman events\n' |
| 359 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 360 | By default, all communication is in bytes, and therefore any "input" |
| 361 | should be bytes, and the return value wil be bytes. If in text mode, |
| 362 | any "input" should be a string, and the return value will be a string |
| 363 | decoded according to locale encoding, or by "encoding" if set. Text mode |
| 364 | is triggered by setting any of text, encoding, errors or universal_newlines. |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 365 | """ |
| 366 | if 'stdout' in kwargs: |
| 367 | raise ValueError('stdout argument not allowed, it will be overridden.') |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 368 | |
| 369 | if 'input' in kwargs and kwargs['input'] is None: |
| 370 | # Explicitly passing input=None was previously equivalent to passing an |
| 371 | # empty string. That is maintained here for backwards compatibility. |
| 372 | kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b'' |
| 373 | |
| 374 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, |
| 375 | **kwargs).stdout |
| 376 | |
| 377 | |
| 378 | class CompletedProcess(object): |
| 379 | """A process that has finished running. |
| 380 | |
| 381 | This is returned by run(). |
| 382 | |
| 383 | Attributes: |
| 384 | args: The list or str args passed to run(). |
| 385 | returncode: The exit code of the process, negative for signals. |
| 386 | stdout: The standard output (None if not captured). |
| 387 | stderr: The standard error (None if not captured). |
| 388 | """ |
| 389 | def __init__(self, args, returncode, stdout=None, stderr=None): |
| 390 | self.args = args |
| 391 | self.returncode = returncode |
| 392 | self.stdout = stdout |
| 393 | self.stderr = stderr |
| 394 | |
| 395 | def __repr__(self): |
| 396 | args = ['args={!r}'.format(self.args), |
| 397 | 'returncode={!r}'.format(self.returncode)] |
| 398 | if self.stdout is not None: |
| 399 | args.append('stdout={!r}'.format(self.stdout)) |
| 400 | if self.stderr is not None: |
| 401 | args.append('stderr={!r}'.format(self.stderr)) |
| 402 | return "{}({})".format(type(self).__name__, ', '.join(args)) |
| 403 | |
| 404 | def check_returncode(self): |
| 405 | """Raise CalledProcessError if the exit code is non-zero.""" |
| 406 | if self.returncode: |
| 407 | raise CalledProcessError(self.returncode, self.args, self.stdout, |
| 408 | self.stderr) |
| 409 | |
| 410 | |
| 411 | def run(*popenargs, input=None, timeout=None, check=False, **kwargs): |
| 412 | """Run command with arguments and return a CompletedProcess instance. |
| 413 | |
| 414 | The returned instance will have attributes args, returncode, stdout and |
| 415 | stderr. By default, stdout and stderr are not captured, and those attributes |
| 416 | will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. |
| 417 | |
| 418 | If check is True and the exit code was non-zero, it raises a |
| 419 | CalledProcessError. The CalledProcessError object will have the return code |
| 420 | in the returncode attribute, and output & stderr attributes if those streams |
| 421 | were captured. |
| 422 | |
| 423 | If timeout is given, and the process takes too long, a TimeoutExpired |
| 424 | exception will be raised. |
| 425 | |
| 426 | There is an optional argument "input", allowing you to |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 427 | pass bytes or a string to the subprocess's stdin. If you use this argument |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 428 | you may not also use the Popen constructor's "stdin" argument, as |
| 429 | it will be used internally. |
| 430 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 431 | By default, all communication is in bytes, and therefore any "input" should |
| 432 | be bytes, and the stdout and stderr will be bytes. If in text mode, any |
| 433 | "input" should be a string, and stdout and stderr will be strings decoded |
| 434 | according to locale encoding, or by "encoding" if set. Text mode is |
| 435 | triggered by setting any of text, encoding, errors or universal_newlines. |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 436 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 437 | The other arguments are the same as for the Popen constructor. |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 438 | """ |
| 439 | if input is not None: |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 440 | if 'stdin' in kwargs: |
| 441 | raise ValueError('stdin and input arguments may not both be used.') |
Serhiy Storchaka | fcd9f22 | 2013-04-22 20:20:54 +0300 | [diff] [blame] | 442 | kwargs['stdin'] = PIPE |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 443 | |
| 444 | with Popen(*popenargs, **kwargs) as process: |
Victor Stinner | c15c88c | 2011-09-01 23:45:04 +0200 | [diff] [blame] | 445 | try: |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 446 | stdout, stderr = process.communicate(input, timeout=timeout) |
Victor Stinner | c15c88c | 2011-09-01 23:45:04 +0200 | [diff] [blame] | 447 | except TimeoutExpired: |
| 448 | process.kill() |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 449 | stdout, stderr = process.communicate() |
| 450 | raise TimeoutExpired(process.args, timeout, output=stdout, |
| 451 | stderr=stderr) |
Victor Stinner | c15c88c | 2011-09-01 23:45:04 +0200 | [diff] [blame] | 452 | except: |
| 453 | process.kill() |
| 454 | process.wait() |
| 455 | raise |
| 456 | retcode = process.poll() |
Gregory P. Smith | 6e73000 | 2015-04-14 16:14:25 -0700 | [diff] [blame] | 457 | if check and retcode: |
| 458 | raise CalledProcessError(retcode, process.args, |
| 459 | output=stdout, stderr=stderr) |
| 460 | return CompletedProcess(process.args, retcode, stdout, stderr) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 461 | |
| 462 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 463 | def list2cmdline(seq): |
| 464 | """ |
| 465 | Translate a sequence of arguments into a command line |
| 466 | string, using the same rules as the MS C runtime: |
| 467 | |
| 468 | 1) Arguments are delimited by white space, which is either a |
| 469 | space or a tab. |
| 470 | |
| 471 | 2) A string surrounded by double quotation marks is |
| 472 | interpreted as a single argument, regardless of white space |
Jean-Paul Calderone | 1ddd407 | 2010-06-18 20:03:54 +0000 | [diff] [blame] | 473 | contained within. A quoted string can be embedded in an |
| 474 | argument. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 475 | |
| 476 | 3) A double quotation mark preceded by a backslash is |
| 477 | interpreted as a literal double quotation mark. |
| 478 | |
| 479 | 4) Backslashes are interpreted literally, unless they |
| 480 | immediately precede a double quotation mark. |
| 481 | |
| 482 | 5) If backslashes immediately precede a double quotation mark, |
| 483 | every pair of backslashes is interpreted as a literal |
| 484 | backslash. If the number of backslashes is odd, the last |
| 485 | backslash escapes the next double quotation mark as |
| 486 | described in rule 3. |
| 487 | """ |
| 488 | |
| 489 | # See |
Eric Smith | 3c573af | 2009-11-09 15:23:15 +0000 | [diff] [blame] | 490 | # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx |
| 491 | # or search http://msdn.microsoft.com for |
| 492 | # "Parsing C++ Command-Line Arguments" |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 493 | result = [] |
| 494 | needquote = False |
| 495 | for arg in seq: |
| 496 | bs_buf = [] |
| 497 | |
| 498 | # Add a space to separate this argument from the others |
| 499 | if result: |
| 500 | result.append(' ') |
| 501 | |
Jean-Paul Calderone | 1ddd407 | 2010-06-18 20:03:54 +0000 | [diff] [blame] | 502 | needquote = (" " in arg) or ("\t" in arg) or not arg |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 503 | if needquote: |
| 504 | result.append('"') |
| 505 | |
| 506 | for c in arg: |
| 507 | if c == '\\': |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 508 | # Don't know if we need to double yet. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 509 | bs_buf.append(c) |
| 510 | elif c == '"': |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 511 | # Double backslashes. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 512 | result.append('\\' * len(bs_buf)*2) |
| 513 | bs_buf = [] |
| 514 | result.append('\\"') |
| 515 | else: |
| 516 | # Normal char |
| 517 | if bs_buf: |
| 518 | result.extend(bs_buf) |
| 519 | bs_buf = [] |
| 520 | result.append(c) |
| 521 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 522 | # Add remaining backslashes, if any. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 523 | if bs_buf: |
| 524 | result.extend(bs_buf) |
| 525 | |
| 526 | if needquote: |
Peter Astrand | 7e78ade | 2005-03-03 21:10:23 +0000 | [diff] [blame] | 527 | result.extend(bs_buf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 528 | result.append('"') |
| 529 | |
| 530 | return ''.join(result) |
| 531 | |
| 532 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 533 | # Various tools for executing commands and looking at their output and status. |
| 534 | # |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 535 | |
| 536 | def getstatusoutput(cmd): |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 537 | """Return (exitcode, output) of executing cmd in a shell. |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 538 | |
Tim Golden | 6079814 | 2013-11-05 12:57:25 +0000 | [diff] [blame] | 539 | Execute the string 'cmd' in a shell with 'check_output' and |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 540 | return a 2-tuple (status, output). The locale encoding is used |
| 541 | to decode the output and process newlines. |
Tim Golden | 6079814 | 2013-11-05 12:57:25 +0000 | [diff] [blame] | 542 | |
| 543 | A trailing newline is stripped from the output. |
| 544 | The exit status for the command can be interpreted |
| 545 | according to the rules for the function 'wait'. Example: |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 546 | |
| 547 | >>> import subprocess |
| 548 | >>> subprocess.getstatusoutput('ls /bin/ls') |
| 549 | (0, '/bin/ls') |
| 550 | >>> subprocess.getstatusoutput('cat /bin/junk') |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 551 | (1, 'cat: /bin/junk: No such file or directory') |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 552 | >>> subprocess.getstatusoutput('/bin/junk') |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 553 | (127, 'sh: /bin/junk: not found') |
| 554 | >>> subprocess.getstatusoutput('/bin/kill $$') |
| 555 | (-15, '') |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 556 | """ |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 557 | try: |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 558 | data = check_output(cmd, shell=True, text=True, stderr=STDOUT) |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 559 | exitcode = 0 |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 560 | except CalledProcessError as ex: |
| 561 | data = ex.output |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 562 | exitcode = ex.returncode |
Tim Golden | e004175 | 2013-11-03 12:53:17 +0000 | [diff] [blame] | 563 | if data[-1:] == '\n': |
| 564 | data = data[:-1] |
Gregory P. Smith | 2eb0cb4 | 2017-09-07 16:11:02 -0700 | [diff] [blame] | 565 | return exitcode, data |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 566 | |
| 567 | def getoutput(cmd): |
| 568 | """Return output (stdout or stderr) of executing cmd in a shell. |
| 569 | |
| 570 | Like getstatusoutput(), except the exit status is ignored and the return |
| 571 | value is a string containing the command's output. Example: |
| 572 | |
| 573 | >>> import subprocess |
| 574 | >>> subprocess.getoutput('ls /bin/ls') |
| 575 | '/bin/ls' |
| 576 | """ |
| 577 | return getstatusoutput(cmd)[1] |
| 578 | |
| 579 | |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 580 | _PLATFORM_DEFAULT_CLOSE_FDS = object() |
Gregory P. Smith | f560485 | 2010-12-13 06:45:02 +0000 | [diff] [blame] | 581 | |
| 582 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 583 | class Popen(object): |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 584 | """ Execute a child program in a new process. |
Serhiy Storchaka | 72e7761 | 2014-02-10 19:20:22 +0200 | [diff] [blame] | 585 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 586 | For a complete description of the arguments see the Python documentation. |
| 587 | |
| 588 | Arguments: |
| 589 | args: A string, or a sequence of program arguments. |
| 590 | |
| 591 | bufsize: supplied as the buffering argument to the open() function when |
| 592 | creating the stdin/stdout/stderr pipe file objects |
| 593 | |
| 594 | executable: A replacement program to execute. |
| 595 | |
| 596 | stdin, stdout and stderr: These specify the executed programs' standard |
| 597 | input, standard output and standard error file handles, respectively. |
| 598 | |
| 599 | preexec_fn: (POSIX only) An object to be called in the child process |
| 600 | just before the child is executed. |
| 601 | |
| 602 | close_fds: Controls closing or inheriting of file descriptors. |
| 603 | |
| 604 | shell: If true, the command will be executed through the shell. |
| 605 | |
| 606 | cwd: Sets the current directory before the child is executed. |
| 607 | |
| 608 | env: Defines the environment variables for the new process. |
| 609 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 610 | text: If true, decode stdin, stdout and stderr using the given encoding |
| 611 | (if set) or the system default otherwise. |
| 612 | |
| 613 | universal_newlines: Alias of text, provided for backwards compatibility. |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 614 | |
| 615 | startupinfo and creationflags (Windows only) |
| 616 | |
| 617 | restore_signals (POSIX only) |
| 618 | |
| 619 | start_new_session (POSIX only) |
| 620 | |
| 621 | pass_fds (POSIX only) |
| 622 | |
Martin Panter | 3dca624 | 2016-10-25 23:41:42 +0000 | [diff] [blame] | 623 | encoding and errors: Text mode encoding and error handling to use for |
| 624 | file objects stdin, stdout and stderr. |
| 625 | |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 626 | Attributes: |
| 627 | stdin, stdout, stderr, pid, returncode |
| 628 | """ |
Serhiy Storchaka | 72e7761 | 2014-02-10 19:20:22 +0200 | [diff] [blame] | 629 | _child_created = False # Set here since __del__ checks it |
| 630 | |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 631 | def __init__(self, args, bufsize=-1, executable=None, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 632 | stdin=None, stdout=None, stderr=None, |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 633 | preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 634 | shell=False, cwd=None, env=None, universal_newlines=None, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 635 | startupinfo=None, creationflags=0, |
Gregory P. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 636 | restore_signals=True, start_new_session=False, |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 637 | pass_fds=(), *, encoding=None, errors=None, text=None): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 638 | """Create new Popen instance.""" |
| 639 | _cleanup() |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 640 | # Held while anything is calling waitpid before returncode has been |
| 641 | # updated to prevent clobbering returncode if wait() or poll() are |
| 642 | # called from multiple threads at once. After acquiring the lock, |
| 643 | # code must re-check self.returncode to see if another thread just |
| 644 | # finished a waitpid() call. |
| 645 | self._waitpid_lock = threading.Lock() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 646 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 647 | self._input = None |
| 648 | self._communication_started = False |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 649 | if bufsize is None: |
Gregory P. Smith | a1ed539 | 2013-03-23 11:44:25 -0700 | [diff] [blame] | 650 | bufsize = -1 # Restore default |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 651 | if not isinstance(bufsize, int): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 652 | raise TypeError("bufsize must be an integer") |
| 653 | |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 654 | if _mswindows: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 655 | if preexec_fn is not None: |
| 656 | raise ValueError("preexec_fn is not supported on Windows " |
| 657 | "platforms") |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 658 | any_stdio_set = (stdin is not None or stdout is not None or |
| 659 | stderr is not None) |
| 660 | if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: |
| 661 | if any_stdio_set: |
| 662 | close_fds = False |
| 663 | else: |
| 664 | close_fds = True |
| 665 | elif close_fds and any_stdio_set: |
| 666 | raise ValueError( |
| 667 | "close_fds is not supported on Windows platforms" |
| 668 | " if you redirect stdin/stdout/stderr") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 669 | else: |
| 670 | # POSIX |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 671 | if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS: |
| 672 | close_fds = True |
| 673 | if pass_fds and not close_fds: |
| 674 | warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) |
| 675 | close_fds = True |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 676 | if startupinfo is not None: |
| 677 | raise ValueError("startupinfo is only supported on Windows " |
| 678 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 679 | if creationflags != 0: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 680 | raise ValueError("creationflags is only supported on Windows " |
| 681 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 682 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 683 | self.args = args |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 684 | self.stdin = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 685 | self.stdout = None |
| 686 | self.stderr = None |
| 687 | self.pid = None |
| 688 | self.returncode = None |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 689 | self.encoding = encoding |
| 690 | self.errors = errors |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 691 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 692 | # Validate the combinations of text and universal_newlines |
| 693 | if (text is not None and universal_newlines is not None |
| 694 | and bool(universal_newlines) != bool(text)): |
| 695 | raise SubprocessError('Cannot disambiguate when both text ' |
| 696 | 'and universal_newlines are supplied but ' |
| 697 | 'different. Pass one or the other.') |
| 698 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 699 | # Input and output objects. The general principle is like |
| 700 | # this: |
| 701 | # |
| 702 | # Parent Child |
| 703 | # ------ ----- |
| 704 | # p2cwrite ---stdin---> p2cread |
| 705 | # c2pread <--stdout--- c2pwrite |
| 706 | # errread <--stderr--- errwrite |
| 707 | # |
| 708 | # On POSIX, the child objects are file descriptors. On |
| 709 | # Windows, these are Windows file handles. The parent objects |
| 710 | # are file descriptors on both platforms. The parent objects |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 711 | # are -1 when not using PIPEs. The child objects are -1 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 712 | # when not redirecting. |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 713 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 714 | (p2cread, p2cwrite, |
| 715 | c2pread, c2pwrite, |
| 716 | errread, errwrite) = self._get_handles(stdin, stdout, stderr) |
| 717 | |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 718 | # We wrap OS handles *before* launching the child, otherwise a |
| 719 | # quickly terminating child could make our fds unwrappable |
| 720 | # (see #8458). |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 721 | |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 722 | if _mswindows: |
Florent Xicluna | 3b8bfef | 2010-03-14 12:31:06 +0000 | [diff] [blame] | 723 | if p2cwrite != -1: |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 724 | p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) |
Florent Xicluna | 3b8bfef | 2010-03-14 12:31:06 +0000 | [diff] [blame] | 725 | if c2pread != -1: |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 726 | c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) |
Florent Xicluna | 3b8bfef | 2010-03-14 12:31:06 +0000 | [diff] [blame] | 727 | if errread != -1: |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 728 | errread = msvcrt.open_osfhandle(errread.Detach(), 0) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 729 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 730 | self.text_mode = encoding or errors or text or universal_newlines |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 731 | |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 732 | self._closed_child_pipe_fds = False |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 733 | |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 734 | try: |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 735 | if p2cwrite != -1: |
| 736 | self.stdin = io.open(p2cwrite, 'wb', bufsize) |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 737 | if self.text_mode: |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 738 | self.stdin = io.TextIOWrapper(self.stdin, write_through=True, |
| 739 | line_buffering=(bufsize == 1), |
| 740 | encoding=encoding, errors=errors) |
| 741 | if c2pread != -1: |
| 742 | self.stdout = io.open(c2pread, 'rb', bufsize) |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 743 | if self.text_mode: |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 744 | self.stdout = io.TextIOWrapper(self.stdout, |
| 745 | encoding=encoding, errors=errors) |
| 746 | if errread != -1: |
| 747 | self.stderr = io.open(errread, 'rb', bufsize) |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 748 | if self.text_mode: |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 749 | self.stderr = io.TextIOWrapper(self.stderr, |
| 750 | encoding=encoding, errors=errors) |
| 751 | |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 752 | self._execute_child(args, executable, preexec_fn, close_fds, |
Andrew Svetlov | 592df20 | 2012-08-15 17:36:15 +0300 | [diff] [blame] | 753 | pass_fds, cwd, env, |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 754 | startupinfo, creationflags, shell, |
| 755 | p2cread, p2cwrite, |
| 756 | c2pread, c2pwrite, |
| 757 | errread, errwrite, |
| 758 | restore_signals, start_new_session) |
| 759 | except: |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 760 | # Cleanup if the child failed starting. |
| 761 | for f in filter(None, (self.stdin, self.stdout, self.stderr)): |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 762 | try: |
| 763 | f.close() |
Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 764 | except OSError: |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 765 | pass # Ignore EBADF or other errors. |
| 766 | |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 767 | if not self._closed_child_pipe_fds: |
| 768 | to_close = [] |
| 769 | if stdin == PIPE: |
| 770 | to_close.append(p2cread) |
| 771 | if stdout == PIPE: |
| 772 | to_close.append(c2pwrite) |
| 773 | if stderr == PIPE: |
| 774 | to_close.append(errwrite) |
| 775 | if hasattr(self, '_devnull'): |
| 776 | to_close.append(self._devnull) |
| 777 | for fd in to_close: |
| 778 | try: |
Segev Finer | 4d38517 | 2017-08-18 16:18:13 +0300 | [diff] [blame] | 779 | if _mswindows and isinstance(fd, Handle): |
| 780 | fd.Close() |
| 781 | else: |
| 782 | os.close(fd) |
Gregory P. Smith | 22ba31a | 2013-06-15 18:14:56 -0700 | [diff] [blame] | 783 | except OSError: |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 784 | pass |
Gregory P. Smith | 3d8e776 | 2012-11-10 22:32:22 -0800 | [diff] [blame] | 785 | |
Antoine Pitrou | c998232 | 2011-01-04 19:07:07 +0000 | [diff] [blame] | 786 | raise |
| 787 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 788 | @property |
| 789 | def universal_newlines(self): |
| 790 | # universal_newlines as retained as an alias of text_mode for API |
luzpaz | a5293b4 | 2017-11-05 07:37:50 -0600 | [diff] [blame] | 791 | # compatibility. bpo-31756 |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 792 | return self.text_mode |
| 793 | |
| 794 | @universal_newlines.setter |
| 795 | def universal_newlines(self, universal_newlines): |
| 796 | self.text_mode = bool(universal_newlines) |
| 797 | |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 798 | def _translate_newlines(self, data, encoding, errors): |
| 799 | data = data.decode(encoding, errors) |
Andrew Svetlov | 8286071 | 2012-08-19 22:13:41 +0300 | [diff] [blame] | 800 | return data.replace("\r\n", "\n").replace("\r", "\n") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 801 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 802 | def __enter__(self): |
| 803 | return self |
| 804 | |
| 805 | def __exit__(self, type, value, traceback): |
| 806 | if self.stdout: |
| 807 | self.stdout.close() |
| 808 | if self.stderr: |
| 809 | self.stderr.close() |
Serhiy Storchaka | ab900c2 | 2015-02-28 12:43:08 +0200 | [diff] [blame] | 810 | try: # Flushing a BufferedWriter may raise an error |
| 811 | if self.stdin: |
| 812 | self.stdin.close() |
| 813 | finally: |
| 814 | # Wait for the process to terminate, to avoid zombies. |
| 815 | self.wait() |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 816 | |
Victor Stinner | 9505b03 | 2017-01-06 10:44:44 +0100 | [diff] [blame] | 817 | def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn): |
Serhiy Storchaka | 72e7761 | 2014-02-10 19:20:22 +0200 | [diff] [blame] | 818 | if not self._child_created: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 819 | # We didn't get to successfully create a child process. |
| 820 | return |
Victor Stinner | 5a48e21 | 2016-05-20 12:11:15 +0200 | [diff] [blame] | 821 | if self.returncode is None: |
Victor Stinner | c206f1e | 2016-06-14 16:42:59 +0200 | [diff] [blame] | 822 | # Not reading subprocess exit status creates a zombi process which |
| 823 | # is only destroyed at the parent python process exit |
Victor Stinner | 9505b03 | 2017-01-06 10:44:44 +0100 | [diff] [blame] | 824 | _warn("subprocess %s is still running" % self.pid, |
| 825 | ResourceWarning, source=self) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 826 | # In case the child hasn't been waited on, check if it's done. |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 827 | self._internal_poll(_deadstate=_maxsize) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 828 | if self.returncode is None and _active is not None: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 829 | # Child is still running, keep us alive until we can wait on it. |
| 830 | _active.append(self) |
| 831 | |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 832 | def _get_devnull(self): |
| 833 | if not hasattr(self, '_devnull'): |
| 834 | self._devnull = os.open(os.devnull, os.O_RDWR) |
| 835 | return self._devnull |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 836 | |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 837 | def _stdin_write(self, input): |
| 838 | if input: |
| 839 | try: |
| 840 | self.stdin.write(input) |
| 841 | except BrokenPipeError: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 842 | pass # communicate() must ignore broken pipe errors. |
Victor Stinner | d52aa31 | 2017-06-08 17:30:39 +0200 | [diff] [blame] | 843 | except OSError as exc: |
| 844 | if exc.errno == errno.EINVAL: |
| 845 | # bpo-19612, bpo-30418: On Windows, stdin.write() fails |
| 846 | # with EINVAL if the child process exited or if the child |
| 847 | # process is still running but closed the pipe. |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 848 | pass |
| 849 | else: |
| 850 | raise |
Victor Stinner | d52aa31 | 2017-06-08 17:30:39 +0200 | [diff] [blame] | 851 | |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 852 | try: |
| 853 | self.stdin.close() |
| 854 | except BrokenPipeError: |
| 855 | pass # communicate() must ignore broken pipe errors. |
Victor Stinner | d52aa31 | 2017-06-08 17:30:39 +0200 | [diff] [blame] | 856 | except OSError as exc: |
| 857 | if exc.errno == errno.EINVAL: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 858 | pass |
| 859 | else: |
| 860 | raise |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 861 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 862 | def communicate(self, input=None, timeout=None): |
Joel Schaerer | 88031a9 | 2017-09-13 21:11:20 +0200 | [diff] [blame] | 863 | """Interact with process: Send data to stdin and close it. |
| 864 | Read data from stdout and stderr, until end-of-file is |
| 865 | reached. Wait for process to terminate. |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 866 | |
Andrew Kuchling | 4f7b0c3 | 2014-04-14 15:08:18 -0400 | [diff] [blame] | 867 | The optional "input" argument should be data to be sent to the |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 868 | child process, or None, if no data should be sent to the child. |
| 869 | communicate() returns a tuple (stdout, stderr). |
Andrew Kuchling | 4f7b0c3 | 2014-04-14 15:08:18 -0400 | [diff] [blame] | 870 | |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 871 | By default, all communication is in bytes, and therefore any |
| 872 | "input" should be bytes, and the (stdout, stderr) will be bytes. |
| 873 | If in text mode (indicated by self.text_mode), any "input" should |
| 874 | be a string, and (stdout, stderr) will be strings decoded |
| 875 | according to locale encoding, or by "encoding" if set. Text mode |
| 876 | is triggered by setting any of text, encoding, errors or |
| 877 | universal_newlines. |
Andrew Kuchling | 4f7b0c3 | 2014-04-14 15:08:18 -0400 | [diff] [blame] | 878 | """ |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 879 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 880 | if self._communication_started and input: |
| 881 | raise ValueError("Cannot send input after starting communication") |
| 882 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 883 | # Optimization: If we are not worried about timeouts, we haven't |
| 884 | # started communicating, and we have one or zero pipes, using select() |
| 885 | # or threads is unnecessary. |
Victor Stinner | 7a8d081 | 2011-04-05 13:13:08 +0200 | [diff] [blame] | 886 | if (timeout is None and not self._communication_started and |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 887 | [self.stdin, self.stdout, self.stderr].count(None) >= 2): |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 888 | stdout = None |
| 889 | stderr = None |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 890 | if self.stdin: |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 891 | self._stdin_write(input) |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 892 | elif self.stdout: |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 893 | stdout = self.stdout.read() |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 894 | self.stdout.close() |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 895 | elif self.stderr: |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 896 | stderr = self.stderr.read() |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 897 | self.stderr.close() |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 898 | self.wait() |
Victor Stinner | 7a8d081 | 2011-04-05 13:13:08 +0200 | [diff] [blame] | 899 | else: |
| 900 | if timeout is not None: |
Victor Stinner | 949d8c9 | 2012-05-30 13:30:32 +0200 | [diff] [blame] | 901 | endtime = _time() + timeout |
Victor Stinner | 7a8d081 | 2011-04-05 13:13:08 +0200 | [diff] [blame] | 902 | else: |
| 903 | endtime = None |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 904 | |
Victor Stinner | 7a8d081 | 2011-04-05 13:13:08 +0200 | [diff] [blame] | 905 | try: |
| 906 | stdout, stderr = self._communicate(input, endtime, timeout) |
| 907 | finally: |
| 908 | self._communication_started = True |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 909 | |
Victor Stinner | 7a8d081 | 2011-04-05 13:13:08 +0200 | [diff] [blame] | 910 | sts = self.wait(timeout=self._remaining_time(endtime)) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 911 | |
| 912 | return (stdout, stderr) |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 913 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 914 | |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 915 | def poll(self): |
Martin Panter | 4afdca0 | 2016-10-25 22:20:48 +0000 | [diff] [blame] | 916 | """Check if child process has terminated. Set and return returncode |
| 917 | attribute.""" |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 918 | return self._internal_poll() |
| 919 | |
| 920 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 921 | def _remaining_time(self, endtime): |
| 922 | """Convenience for _communicate when computing timeouts.""" |
| 923 | if endtime is None: |
| 924 | return None |
| 925 | else: |
Victor Stinner | 949d8c9 | 2012-05-30 13:30:32 +0200 | [diff] [blame] | 926 | return endtime - _time() |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 927 | |
| 928 | |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 929 | def _check_timeout(self, endtime, orig_timeout): |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 930 | """Convenience for checking if a timeout has expired.""" |
| 931 | if endtime is None: |
| 932 | return |
Victor Stinner | 949d8c9 | 2012-05-30 13:30:32 +0200 | [diff] [blame] | 933 | if _time() > endtime: |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 934 | raise TimeoutExpired(self.args, orig_timeout) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 935 | |
| 936 | |
Gregory P. Smith | cb6fdf2 | 2015-04-07 16:11:33 -0700 | [diff] [blame] | 937 | if _mswindows: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 938 | # |
| 939 | # Windows methods |
| 940 | # |
| 941 | def _get_handles(self, stdin, stdout, stderr): |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 942 | """Construct and return tuple with IO objects: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 943 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 944 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 945 | if stdin is None and stdout is None and stderr is None: |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 946 | return (-1, -1, -1, -1, -1, -1) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 947 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 948 | p2cread, p2cwrite = -1, -1 |
| 949 | c2pread, c2pwrite = -1, -1 |
| 950 | errread, errwrite = -1, -1 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 951 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 952 | if stdin is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 953 | p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 954 | if p2cread is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 955 | p2cread, _ = _winapi.CreatePipe(None, 0) |
| 956 | p2cread = Handle(p2cread) |
| 957 | _winapi.CloseHandle(_) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 958 | elif stdin == PIPE: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 959 | p2cread, p2cwrite = _winapi.CreatePipe(None, 0) |
| 960 | p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 961 | elif stdin == DEVNULL: |
| 962 | p2cread = msvcrt.get_osfhandle(self._get_devnull()) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 963 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 964 | p2cread = msvcrt.get_osfhandle(stdin) |
| 965 | else: |
| 966 | # Assuming file-like object |
| 967 | p2cread = msvcrt.get_osfhandle(stdin.fileno()) |
| 968 | p2cread = self._make_inheritable(p2cread) |
| 969 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 970 | if stdout is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 971 | c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 972 | if c2pwrite is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 973 | _, c2pwrite = _winapi.CreatePipe(None, 0) |
| 974 | c2pwrite = Handle(c2pwrite) |
| 975 | _winapi.CloseHandle(_) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 976 | elif stdout == PIPE: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 977 | c2pread, c2pwrite = _winapi.CreatePipe(None, 0) |
| 978 | c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 979 | elif stdout == DEVNULL: |
| 980 | c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 981 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 982 | c2pwrite = msvcrt.get_osfhandle(stdout) |
| 983 | else: |
| 984 | # Assuming file-like object |
| 985 | c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) |
| 986 | c2pwrite = self._make_inheritable(c2pwrite) |
| 987 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 988 | if stderr is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 989 | errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 990 | if errwrite is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 991 | _, errwrite = _winapi.CreatePipe(None, 0) |
| 992 | errwrite = Handle(errwrite) |
| 993 | _winapi.CloseHandle(_) |
Hirokazu Yamamoto | 0c98817 | 2009-03-03 22:41:26 +0000 | [diff] [blame] | 994 | elif stderr == PIPE: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 995 | errread, errwrite = _winapi.CreatePipe(None, 0) |
| 996 | errread, errwrite = Handle(errread), Handle(errwrite) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 997 | elif stderr == STDOUT: |
| 998 | errwrite = c2pwrite |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 999 | elif stderr == DEVNULL: |
| 1000 | errwrite = msvcrt.get_osfhandle(self._get_devnull()) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1001 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1002 | errwrite = msvcrt.get_osfhandle(stderr) |
| 1003 | else: |
| 1004 | # Assuming file-like object |
| 1005 | errwrite = msvcrt.get_osfhandle(stderr.fileno()) |
| 1006 | errwrite = self._make_inheritable(errwrite) |
| 1007 | |
| 1008 | return (p2cread, p2cwrite, |
| 1009 | c2pread, c2pwrite, |
| 1010 | errread, errwrite) |
| 1011 | |
| 1012 | |
| 1013 | def _make_inheritable(self, handle): |
| 1014 | """Return a duplicate of handle, which is inheritable""" |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1015 | h = _winapi.DuplicateHandle( |
| 1016 | _winapi.GetCurrentProcess(), handle, |
| 1017 | _winapi.GetCurrentProcess(), 0, 1, |
| 1018 | _winapi.DUPLICATE_SAME_ACCESS) |
| 1019 | return Handle(h) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1020 | |
| 1021 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1022 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
Andrew Svetlov | 592df20 | 2012-08-15 17:36:15 +0300 | [diff] [blame] | 1023 | pass_fds, cwd, env, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1024 | startupinfo, creationflags, shell, |
| 1025 | p2cread, p2cwrite, |
| 1026 | c2pread, c2pwrite, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1027 | errread, errwrite, |
| 1028 | unused_restore_signals, unused_start_new_session): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1029 | """Execute program (MS Windows version)""" |
| 1030 | |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 1031 | assert not pass_fds, "pass_fds not supported on Windows." |
Gregory P. Smith | d4cc7bf | 2010-12-04 11:22:11 +0000 | [diff] [blame] | 1032 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1033 | if not isinstance(args, str): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1034 | args = list2cmdline(args) |
| 1035 | |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 1036 | # Process startup details |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1037 | if startupinfo is None: |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 1038 | startupinfo = STARTUPINFO() |
Victor Stinner | b369358 | 2010-05-21 20:13:12 +0000 | [diff] [blame] | 1039 | if -1 not in (p2cread, c2pwrite, errwrite): |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1040 | startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 1041 | startupinfo.hStdInput = p2cread |
| 1042 | startupinfo.hStdOutput = c2pwrite |
| 1043 | startupinfo.hStdError = errwrite |
| 1044 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1045 | if shell: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1046 | startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW |
| 1047 | startupinfo.wShowWindow = _winapi.SW_HIDE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1048 | comspec = os.environ.get("COMSPEC", "cmd.exe") |
Tim Golden | 126c296 | 2010-08-11 14:20:40 +0000 | [diff] [blame] | 1049 | args = '{} /c "{}"'.format (comspec, args) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1050 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1051 | # Start the process |
| 1052 | try: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1053 | hp, ht, pid, tid = _winapi.CreateProcess(executable, args, |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 1054 | # no special security |
| 1055 | None, None, |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1056 | int(not close_fds), |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 1057 | creationflags, |
| 1058 | env, |
Benjamin Peterson | cb90f26 | 2017-03-02 00:03:41 -0800 | [diff] [blame] | 1059 | os.fspath(cwd) if cwd is not None else None, |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 1060 | startupinfo) |
Tim Golden | ad537f2 | 2010-08-08 11:18:16 +0000 | [diff] [blame] | 1061 | finally: |
| 1062 | # Child is launched. Close the parent's copy of those pipe |
| 1063 | # handles that only the child should have open. You need |
| 1064 | # to make sure that no handles to the write end of the |
| 1065 | # output pipe are maintained in this process or else the |
| 1066 | # pipe will not close when the child process exits and the |
| 1067 | # ReadFile will hang. |
| 1068 | if p2cread != -1: |
| 1069 | p2cread.Close() |
| 1070 | if c2pwrite != -1: |
| 1071 | c2pwrite.Close() |
| 1072 | if errwrite != -1: |
| 1073 | errwrite.Close() |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 1074 | if hasattr(self, '_devnull'): |
| 1075 | os.close(self._devnull) |
Segev Finer | 4d38517 | 2017-08-18 16:18:13 +0300 | [diff] [blame] | 1076 | # Prevent a double close of these handles/fds from __init__ |
| 1077 | # on error. |
| 1078 | self._closed_child_pipe_fds = True |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1079 | |
| 1080 | # Retain the process handle, but close the thread handle |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1081 | self._child_created = True |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1082 | self._handle = Handle(hp) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1083 | self.pid = pid |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1084 | _winapi.CloseHandle(ht) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1085 | |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1086 | def _internal_poll(self, _deadstate=None, |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1087 | _WaitForSingleObject=_winapi.WaitForSingleObject, |
| 1088 | _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0, |
| 1089 | _GetExitCodeProcess=_winapi.GetExitCodeProcess): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1090 | """Check if child process has terminated. Returns returncode |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1091 | attribute. |
| 1092 | |
| 1093 | This method is called by __del__, so it can only refer to objects |
| 1094 | in its local scope. |
| 1095 | |
| 1096 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1097 | if self.returncode is None: |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1098 | if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: |
| 1099 | self.returncode = _GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1100 | return self.returncode |
| 1101 | |
| 1102 | |
Gregory P. Smith | 82604e0 | 2016-11-20 16:31:07 -0800 | [diff] [blame] | 1103 | def wait(self, timeout=None): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1104 | """Wait for child process to terminate. Returns returncode |
| 1105 | attribute.""" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1106 | if timeout is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1107 | timeout_millis = _winapi.INFINITE |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1108 | else: |
Reid Kleckner | 91156ff | 2011-03-21 10:06:10 -0700 | [diff] [blame] | 1109 | timeout_millis = int(timeout * 1000) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1110 | if self.returncode is None: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1111 | result = _winapi.WaitForSingleObject(self._handle, |
| 1112 | timeout_millis) |
| 1113 | if result == _winapi.WAIT_TIMEOUT: |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1114 | raise TimeoutExpired(self.args, timeout) |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1115 | self.returncode = _winapi.GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1116 | return self.returncode |
| 1117 | |
| 1118 | |
| 1119 | def _readerthread(self, fh, buffer): |
| 1120 | buffer.append(fh.read()) |
Victor Stinner | 667d4b5 | 2010-12-25 22:40:32 +0000 | [diff] [blame] | 1121 | fh.close() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1122 | |
| 1123 | |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1124 | def _communicate(self, input, endtime, orig_timeout): |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1125 | # Start reader threads feeding into a list hanging off of this |
| 1126 | # object, unless they've already been started. |
| 1127 | if self.stdout and not hasattr(self, "_stdout_buff"): |
| 1128 | self._stdout_buff = [] |
| 1129 | self.stdout_thread = \ |
| 1130 | threading.Thread(target=self._readerthread, |
| 1131 | args=(self.stdout, self._stdout_buff)) |
| 1132 | self.stdout_thread.daemon = True |
| 1133 | self.stdout_thread.start() |
| 1134 | if self.stderr and not hasattr(self, "_stderr_buff"): |
| 1135 | self._stderr_buff = [] |
| 1136 | self.stderr_thread = \ |
| 1137 | threading.Thread(target=self._readerthread, |
| 1138 | args=(self.stderr, self._stderr_buff)) |
| 1139 | self.stderr_thread.daemon = True |
| 1140 | self.stderr_thread.start() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1141 | |
| 1142 | if self.stdin: |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 1143 | self._stdin_write(input) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1144 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1145 | # Wait for the reader threads, or time out. If we time out, the |
| 1146 | # threads remain reading and the fds left open in case the user |
| 1147 | # calls communicate again. |
| 1148 | if self.stdout is not None: |
| 1149 | self.stdout_thread.join(self._remaining_time(endtime)) |
Andrew Svetlov | 377a152 | 2012-08-19 20:49:39 +0300 | [diff] [blame] | 1150 | if self.stdout_thread.is_alive(): |
Reid Kleckner | 9a67e6c | 2011-03-20 08:28:07 -0700 | [diff] [blame] | 1151 | raise TimeoutExpired(self.args, orig_timeout) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1152 | if self.stderr is not None: |
| 1153 | self.stderr_thread.join(self._remaining_time(endtime)) |
Andrew Svetlov | 377a152 | 2012-08-19 20:49:39 +0300 | [diff] [blame] | 1154 | if self.stderr_thread.is_alive(): |
Reid Kleckner | 9a67e6c | 2011-03-20 08:28:07 -0700 | [diff] [blame] | 1155 | raise TimeoutExpired(self.args, orig_timeout) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1156 | |
| 1157 | # Collect the output from and close both pipes, now that we know |
| 1158 | # both have been read successfully. |
| 1159 | stdout = None |
| 1160 | stderr = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1161 | if self.stdout: |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1162 | stdout = self._stdout_buff |
| 1163 | self.stdout.close() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1164 | if self.stderr: |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1165 | stderr = self._stderr_buff |
| 1166 | self.stderr.close() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1167 | |
| 1168 | # All data exchanged. Translate lists into strings. |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1169 | if stdout is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1170 | stdout = stdout[0] |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1171 | if stderr is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1172 | stderr = stderr[0] |
| 1173 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1174 | return (stdout, stderr) |
| 1175 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1176 | def send_signal(self, sig): |
Gregory P. Smith | a0c9caa | 2015-11-15 18:19:10 -0800 | [diff] [blame] | 1177 | """Send a signal to the process.""" |
| 1178 | # Don't signal a process that we know has already died. |
| 1179 | if self.returncode is not None: |
| 1180 | return |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1181 | if sig == signal.SIGTERM: |
| 1182 | self.terminate() |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1183 | elif sig == signal.CTRL_C_EVENT: |
| 1184 | os.kill(self.pid, signal.CTRL_C_EVENT) |
| 1185 | elif sig == signal.CTRL_BREAK_EVENT: |
| 1186 | os.kill(self.pid, signal.CTRL_BREAK_EVENT) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1187 | else: |
Brian Curtin | 1965136 | 2010-09-07 13:24:38 +0000 | [diff] [blame] | 1188 | raise ValueError("Unsupported signal: {}".format(sig)) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1189 | |
| 1190 | def terminate(self): |
Gregory P. Smith | a0c9caa | 2015-11-15 18:19:10 -0800 | [diff] [blame] | 1191 | """Terminates the process.""" |
| 1192 | # Don't terminate a process that we know has already died. |
| 1193 | if self.returncode is not None: |
| 1194 | return |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1195 | try: |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1196 | _winapi.TerminateProcess(self._handle, 1) |
Antoine Pitrou | b69ef16 | 2012-03-11 19:33:29 +0100 | [diff] [blame] | 1197 | except PermissionError: |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1198 | # ERROR_ACCESS_DENIED (winerror 5) is received when the |
| 1199 | # process already died. |
Antoine Pitrou | 23bba4c | 2012-04-18 20:51:15 +0200 | [diff] [blame] | 1200 | rc = _winapi.GetExitCodeProcess(self._handle) |
| 1201 | if rc == _winapi.STILL_ACTIVE: |
Antoine Pitrou | 1f9a835 | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1202 | raise |
| 1203 | self.returncode = rc |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1204 | |
| 1205 | kill = terminate |
| 1206 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1207 | else: |
| 1208 | # |
| 1209 | # POSIX methods |
| 1210 | # |
| 1211 | def _get_handles(self, stdin, stdout, stderr): |
Alexandre Vassalotti | 711ed4a | 2009-07-17 10:42:05 +0000 | [diff] [blame] | 1212 | """Construct and return tuple with IO objects: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1213 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 1214 | """ |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1215 | p2cread, p2cwrite = -1, -1 |
| 1216 | c2pread, c2pwrite = -1, -1 |
| 1217 | errread, errwrite = -1, -1 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1218 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1219 | if stdin is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1220 | pass |
| 1221 | elif stdin == PIPE: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1222 | p2cread, p2cwrite = os.pipe() |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 1223 | elif stdin == DEVNULL: |
| 1224 | p2cread = self._get_devnull() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1225 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1226 | p2cread = stdin |
| 1227 | else: |
| 1228 | # Assuming file-like object |
| 1229 | p2cread = stdin.fileno() |
| 1230 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1231 | if stdout is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1232 | pass |
| 1233 | elif stdout == PIPE: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1234 | c2pread, c2pwrite = os.pipe() |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 1235 | elif stdout == DEVNULL: |
| 1236 | c2pwrite = self._get_devnull() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1237 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1238 | c2pwrite = stdout |
| 1239 | else: |
| 1240 | # Assuming file-like object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1241 | c2pwrite = stdout.fileno() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1242 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1243 | if stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1244 | pass |
| 1245 | elif stderr == PIPE: |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1246 | errread, errwrite = os.pipe() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1247 | elif stderr == STDOUT: |
Martin Panter | c763589 | 2016-05-13 01:54:44 +0000 | [diff] [blame] | 1248 | if c2pwrite != -1: |
| 1249 | errwrite = c2pwrite |
| 1250 | else: # child's stdout is not set, use parent's stdout |
| 1251 | errwrite = sys.__stdout__.fileno() |
Ross Lagerwall | ba102ec | 2011-03-16 18:40:25 +0200 | [diff] [blame] | 1252 | elif stderr == DEVNULL: |
| 1253 | errwrite = self._get_devnull() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1254 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1255 | errwrite = stderr |
| 1256 | else: |
| 1257 | # Assuming file-like object |
| 1258 | errwrite = stderr.fileno() |
| 1259 | |
| 1260 | return (p2cread, p2cwrite, |
| 1261 | c2pread, c2pwrite, |
| 1262 | errread, errwrite) |
| 1263 | |
| 1264 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1265 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
Andrew Svetlov | 592df20 | 2012-08-15 17:36:15 +0300 | [diff] [blame] | 1266 | pass_fds, cwd, env, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1267 | startupinfo, creationflags, shell, |
| 1268 | p2cread, p2cwrite, |
| 1269 | c2pread, c2pwrite, |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1270 | errread, errwrite, |
| 1271 | restore_signals, start_new_session): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1272 | """Execute program (POSIX version)""" |
| 1273 | |
Victor Stinner | 7b3b20a | 2011-03-03 12:54:05 +0000 | [diff] [blame] | 1274 | if isinstance(args, (str, bytes)): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1275 | args = [args] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1276 | else: |
| 1277 | args = list(args) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1278 | |
| 1279 | if shell: |
Xavier de Gaye | b35fc62 | 2016-12-13 16:32:21 +0100 | [diff] [blame] | 1280 | # On Android the default shell is at '/system/bin/sh'. |
| 1281 | unix_shell = ('/system/bin/sh' if |
| 1282 | hasattr(sys, 'getandroidapilevel') else '/bin/sh') |
| 1283 | args = [unix_shell, "-c"] + args |
Stefan Krah | 9542cc6 | 2010-07-19 14:20:53 +0000 | [diff] [blame] | 1284 | if executable: |
| 1285 | args[0] = executable |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1286 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1287 | if executable is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1288 | executable = args[0] |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1289 | orig_executable = executable |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1290 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1291 | # For transferring possible exec failure from child to parent. |
| 1292 | # Data format: "exception name:hex errno:description" |
| 1293 | # Pickle is not used; it is complex and involves memory allocation. |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 1294 | errpipe_read, errpipe_write = os.pipe() |
Gregory P. Smith | 53dd816 | 2013-12-01 16:03:24 -0800 | [diff] [blame] | 1295 | # errpipe_write must not be in the standard io 0, 1, or 2 fd range. |
| 1296 | low_fds_to_close = [] |
| 1297 | while errpipe_write < 3: |
| 1298 | low_fds_to_close.append(errpipe_write) |
| 1299 | errpipe_write = os.dup(errpipe_write) |
| 1300 | for low_fd in low_fds_to_close: |
| 1301 | os.close(low_fd) |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 1302 | try: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1303 | try: |
Gregory P. Smith | 59fd1bf | 2011-05-28 09:32:39 -0700 | [diff] [blame] | 1304 | # We must avoid complex work that could involve |
| 1305 | # malloc or free in the child process to avoid |
| 1306 | # potential deadlocks, thus we do all this here. |
| 1307 | # and pass it to fork_exec() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1308 | |
Victor Stinner | 372b838 | 2011-06-21 17:24:21 +0200 | [diff] [blame] | 1309 | if env is not None: |
Serhiy Storchaka | d174d24 | 2017-06-23 19:39:27 +0300 | [diff] [blame] | 1310 | env_list = [] |
| 1311 | for k, v in env.items(): |
| 1312 | k = os.fsencode(k) |
| 1313 | if b'=' in k: |
| 1314 | raise ValueError("illegal environment variable name") |
| 1315 | env_list.append(k + b'=' + os.fsencode(v)) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1316 | else: |
Gregory P. Smith | 59fd1bf | 2011-05-28 09:32:39 -0700 | [diff] [blame] | 1317 | env_list = None # Use execv instead of execve. |
| 1318 | executable = os.fsencode(executable) |
| 1319 | if os.path.dirname(executable): |
| 1320 | executable_list = (executable,) |
| 1321 | else: |
| 1322 | # This matches the behavior of os._execvpe(). |
| 1323 | executable_list = tuple( |
| 1324 | os.path.join(os.fsencode(dir), executable) |
| 1325 | for dir in os.get_exec_path(env)) |
Gregory P. Smith | 361e30c | 2013-12-01 00:12:24 -0800 | [diff] [blame] | 1326 | fds_to_keep = set(pass_fds) |
Gregory P. Smith | 59fd1bf | 2011-05-28 09:32:39 -0700 | [diff] [blame] | 1327 | fds_to_keep.add(errpipe_write) |
| 1328 | self.pid = _posixsubprocess.fork_exec( |
| 1329 | args, executable_list, |
Serhiy Storchaka | 66bffd1 | 2017-04-19 21:12:46 +0300 | [diff] [blame] | 1330 | close_fds, tuple(sorted(map(int, fds_to_keep))), |
| 1331 | cwd, env_list, |
Gregory P. Smith | 59fd1bf | 2011-05-28 09:32:39 -0700 | [diff] [blame] | 1332 | p2cread, p2cwrite, c2pread, c2pwrite, |
| 1333 | errread, errwrite, |
| 1334 | errpipe_read, errpipe_write, |
| 1335 | restore_signals, start_new_session, preexec_fn) |
Charles-François Natali | 558639f | 2011-08-18 19:11:29 +0200 | [diff] [blame] | 1336 | self._child_created = True |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1337 | finally: |
| 1338 | # be sure the FD is closed no matter what |
| 1339 | os.close(errpipe_write) |
| 1340 | |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 1341 | # self._devnull is not always defined. |
| 1342 | devnull_fd = getattr(self, '_devnull', None) |
| 1343 | if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1344 | os.close(p2cread) |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 1345 | if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1346 | os.close(c2pwrite) |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 1347 | if errwrite != -1 and errread != -1 and errwrite != devnull_fd: |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1348 | os.close(errwrite) |
Gregory P. Smith | b5461b9 | 2013-06-15 18:04:26 -0700 | [diff] [blame] | 1349 | if devnull_fd is not None: |
| 1350 | os.close(devnull_fd) |
| 1351 | # Prevent a double close of these fds from __init__ on error. |
| 1352 | self._closed_child_pipe_fds = True |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1353 | |
| 1354 | # Wait for exec to fail or succeed; possibly raising an |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1355 | # exception (limited in size) |
Gregory P. Smith | f44c9da | 2012-11-10 23:33:17 -0800 | [diff] [blame] | 1356 | errpipe_data = bytearray() |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1357 | while True: |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 1358 | part = os.read(errpipe_read, 50000) |
Gregory P. Smith | f44c9da | 2012-11-10 23:33:17 -0800 | [diff] [blame] | 1359 | errpipe_data += part |
| 1360 | if not part or len(errpipe_data) > 50000: |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1361 | break |
Facundo Batista | 10706e2 | 2009-06-19 20:34:30 +0000 | [diff] [blame] | 1362 | finally: |
| 1363 | # be sure the FD is closed no matter what |
| 1364 | os.close(errpipe_read) |
| 1365 | |
Gregory P. Smith | f44c9da | 2012-11-10 23:33:17 -0800 | [diff] [blame] | 1366 | if errpipe_data: |
Gregory P. Smith | e85db2b | 2010-12-14 14:38:00 +0000 | [diff] [blame] | 1367 | try: |
Victor Stinner | a58e2c5 | 2016-05-20 12:08:12 +0200 | [diff] [blame] | 1368 | pid, sts = os.waitpid(self.pid, 0) |
| 1369 | if pid == self.pid: |
| 1370 | self._handle_exitstatus(sts) |
| 1371 | else: |
| 1372 | self.returncode = sys.maxsize |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 1373 | except ChildProcessError: |
| 1374 | pass |
Victor Stinner | a58e2c5 | 2016-05-20 12:08:12 +0200 | [diff] [blame] | 1375 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1376 | try: |
Gregory P. Smith | f44c9da | 2012-11-10 23:33:17 -0800 | [diff] [blame] | 1377 | exception_name, hex_errno, err_msg = ( |
| 1378 | errpipe_data.split(b':', 2)) |
Ammar Askar | 3fc499b | 2017-09-06 02:41:30 -0400 | [diff] [blame] | 1379 | # The encoding here should match the encoding |
| 1380 | # written in by the subprocess implementations |
| 1381 | # like _posixsubprocess |
| 1382 | err_msg = err_msg.decode() |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1383 | except ValueError: |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1384 | exception_name = b'SubprocessError' |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1385 | hex_errno = b'0' |
Ammar Askar | 3fc499b | 2017-09-06 02:41:30 -0400 | [diff] [blame] | 1386 | err_msg = 'Bad exception data from child: {!r}'.format( |
| 1387 | bytes(errpipe_data)) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1388 | child_exception_type = getattr( |
| 1389 | builtins, exception_name.decode('ascii'), |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1390 | SubprocessError) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1391 | if issubclass(child_exception_type, OSError) and hex_errno: |
Benjamin Peterson | b8bc439 | 2010-11-20 18:24:54 +0000 | [diff] [blame] | 1392 | errno_num = int(hex_errno, 16) |
Gregory P. Smith | 5591b02 | 2012-10-10 03:34:47 -0700 | [diff] [blame] | 1393 | child_exec_never_called = (err_msg == "noexec") |
| 1394 | if child_exec_never_called: |
| 1395 | err_msg = "" |
Gregory P. Smith | 8621bb5 | 2017-08-24 14:58:25 -0700 | [diff] [blame] | 1396 | # The error must be from chdir(cwd). |
| 1397 | err_filename = cwd |
| 1398 | else: |
| 1399 | err_filename = orig_executable |
Benjamin Peterson | b8bc439 | 2010-11-20 18:24:54 +0000 | [diff] [blame] | 1400 | if errno_num != 0: |
| 1401 | err_msg = os.strerror(errno_num) |
| 1402 | if errno_num == errno.ENOENT: |
Gregory P. Smith | 8621bb5 | 2017-08-24 14:58:25 -0700 | [diff] [blame] | 1403 | err_msg += ': ' + repr(err_filename) |
| 1404 | raise child_exception_type(errno_num, err_msg, err_filename) |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 1405 | raise child_exception_type(err_msg) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1406 | |
| 1407 | |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1408 | def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, |
| 1409 | _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, |
Gregory P. Smith | 50e16e3 | 2017-01-22 17:28:38 -0800 | [diff] [blame] | 1410 | _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED, |
| 1411 | _WSTOPSIG=os.WSTOPSIG): |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1412 | """All callers to this function MUST hold self._waitpid_lock.""" |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1413 | # This method is called (indirectly) by __del__, so it cannot |
Serhiy Storchaka | 72e7761 | 2014-02-10 19:20:22 +0200 | [diff] [blame] | 1414 | # refer to anything outside of its local scope. |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1415 | if _WIFSIGNALED(sts): |
| 1416 | self.returncode = -_WTERMSIG(sts) |
| 1417 | elif _WIFEXITED(sts): |
| 1418 | self.returncode = _WEXITSTATUS(sts) |
Gregory P. Smith | 50e16e3 | 2017-01-22 17:28:38 -0800 | [diff] [blame] | 1419 | elif _WIFSTOPPED(sts): |
| 1420 | self.returncode = -_WSTOPSIG(sts) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1421 | else: |
| 1422 | # Should never happen |
Gregory P. Smith | 8d07c26 | 2012-11-10 23:53:47 -0800 | [diff] [blame] | 1423 | raise SubprocessError("Unknown child exit status!") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1424 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1425 | |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1426 | def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, |
Andrew Svetlov | 1d960fe | 2012-12-24 20:08:53 +0200 | [diff] [blame] | 1427 | _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1428 | """Check if child process has terminated. Returns returncode |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1429 | attribute. |
| 1430 | |
| 1431 | This method is called by __del__, so it cannot reference anything |
| 1432 | outside of the local scope (nor can any methods it calls). |
| 1433 | |
| 1434 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1435 | if self.returncode is None: |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1436 | if not self._waitpid_lock.acquire(False): |
| 1437 | # Something else is busy calling waitpid. Don't allow two |
| 1438 | # at once. We know nothing yet. |
| 1439 | return None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1440 | try: |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1441 | if self.returncode is not None: |
| 1442 | return self.returncode # Another thread waited. |
Brett Cannon | 84df1e6 | 2010-05-14 00:33:40 +0000 | [diff] [blame] | 1443 | pid, sts = _waitpid(self.pid, _WNOHANG) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1444 | if pid == self.pid: |
| 1445 | self._handle_exitstatus(sts) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 1446 | except OSError as e: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1447 | if _deadstate is not None: |
| 1448 | self.returncode = _deadstate |
Andrew Svetlov | 08bab07 | 2012-12-24 20:06:35 +0200 | [diff] [blame] | 1449 | elif e.errno == _ECHILD: |
Gregory P. Smith | 3905171 | 2012-09-29 11:40:38 -0700 | [diff] [blame] | 1450 | # This happens if SIGCLD is set to be ignored or |
| 1451 | # waiting for child processes has otherwise been |
| 1452 | # disabled for our process. This child is dead, we |
| 1453 | # can't get the status. |
| 1454 | # http://bugs.python.org/issue15756 |
| 1455 | self.returncode = 0 |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1456 | finally: |
| 1457 | self._waitpid_lock.release() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1458 | return self.returncode |
| 1459 | |
| 1460 | |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1461 | def _try_wait(self, wait_flags): |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1462 | """All callers to this function MUST hold self._waitpid_lock.""" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1463 | try: |
Charles-François Natali | 6e6c59b | 2015-02-07 13:27:50 +0000 | [diff] [blame] | 1464 | (pid, sts) = os.waitpid(self.pid, wait_flags) |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 1465 | except ChildProcessError: |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1466 | # This happens if SIGCLD is set to be ignored or waiting |
| 1467 | # for child processes has otherwise been disabled for our |
| 1468 | # process. This child is dead, we can't get the status. |
| 1469 | pid = self.pid |
| 1470 | sts = 0 |
| 1471 | return (pid, sts) |
| 1472 | |
| 1473 | |
Gregory P. Smith | 82604e0 | 2016-11-20 16:31:07 -0800 | [diff] [blame] | 1474 | def wait(self, timeout=None): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1475 | """Wait for child process to terminate. Returns returncode |
| 1476 | attribute.""" |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1477 | if self.returncode is not None: |
| 1478 | return self.returncode |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1479 | |
Gregory P. Smith | 82604e0 | 2016-11-20 16:31:07 -0800 | [diff] [blame] | 1480 | if timeout is not None: |
| 1481 | endtime = _time() + timeout |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1482 | # Enter a busy loop if we have a timeout. This busy loop was |
| 1483 | # cribbed from Lib/threading.py in Thread.wait() at r71065. |
| 1484 | delay = 0.0005 # 500 us -> initial delay of 1 ms |
| 1485 | while True: |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1486 | if self._waitpid_lock.acquire(False): |
| 1487 | try: |
| 1488 | if self.returncode is not None: |
| 1489 | break # Another thread waited. |
| 1490 | (pid, sts) = self._try_wait(os.WNOHANG) |
| 1491 | assert pid == self.pid or pid == 0 |
| 1492 | if pid == self.pid: |
| 1493 | self._handle_exitstatus(sts) |
| 1494 | break |
| 1495 | finally: |
| 1496 | self._waitpid_lock.release() |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1497 | remaining = self._remaining_time(endtime) |
| 1498 | if remaining <= 0: |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1499 | raise TimeoutExpired(self.args, timeout) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1500 | delay = min(delay * 2, remaining, .05) |
| 1501 | time.sleep(delay) |
Gregory P. Smith | f328d79 | 2012-11-10 21:06:18 -0800 | [diff] [blame] | 1502 | else: |
| 1503 | while self.returncode is None: |
Gregory P. Smith | d65ba51 | 2014-04-23 00:27:17 -0700 | [diff] [blame] | 1504 | with self._waitpid_lock: |
| 1505 | if self.returncode is not None: |
| 1506 | break # Another thread waited. |
| 1507 | (pid, sts) = self._try_wait(0) |
| 1508 | # Check the pid and loop as waitpid has been known to |
| 1509 | # return 0 even without WNOHANG in odd situations. |
| 1510 | # http://bugs.python.org/issue14396. |
| 1511 | if pid == self.pid: |
| 1512 | self._handle_exitstatus(sts) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1513 | return self.returncode |
| 1514 | |
| 1515 | |
Reid Kleckner | 2b228f0 | 2011-03-16 16:57:54 -0400 | [diff] [blame] | 1516 | def _communicate(self, input, endtime, orig_timeout): |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1517 | if self.stdin and not self._communication_started: |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1518 | # Flush stdio buffer. This might block, if the user has |
| 1519 | # been writing to .stdin in an uncontrolled fashion. |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 1520 | try: |
| 1521 | self.stdin.flush() |
| 1522 | except BrokenPipeError: |
| 1523 | pass # communicate() must ignore BrokenPipeError. |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1524 | if not input: |
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D) | 1ef8c7e | 2016-06-04 00:22:17 +0000 | [diff] [blame] | 1525 | try: |
| 1526 | self.stdin.close() |
| 1527 | except BrokenPipeError: |
| 1528 | pass # communicate() must ignore BrokenPipeError. |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1529 | |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 1530 | stdout = None |
| 1531 | stderr = None |
| 1532 | |
| 1533 | # Only create this mapping if we haven't already. |
| 1534 | if not self._communication_started: |
| 1535 | self._fileobj2output = {} |
| 1536 | if self.stdout: |
| 1537 | self._fileobj2output[self.stdout] = [] |
| 1538 | if self.stderr: |
| 1539 | self._fileobj2output[self.stderr] = [] |
| 1540 | |
| 1541 | if self.stdout: |
| 1542 | stdout = self._fileobj2output[self.stdout] |
| 1543 | if self.stderr: |
| 1544 | stderr = self._fileobj2output[self.stderr] |
| 1545 | |
| 1546 | self._save_input(input) |
| 1547 | |
Gregory P. Smith | 5ca129b | 2013-12-07 19:14:59 -0800 | [diff] [blame] | 1548 | if self._input: |
| 1549 | input_view = memoryview(self._input) |
| 1550 | |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 1551 | with _PopenSelector() as selector: |
| 1552 | if self.stdin and input: |
| 1553 | selector.register(self.stdin, selectors.EVENT_WRITE) |
| 1554 | if self.stdout: |
| 1555 | selector.register(self.stdout, selectors.EVENT_READ) |
| 1556 | if self.stderr: |
| 1557 | selector.register(self.stderr, selectors.EVENT_READ) |
| 1558 | |
| 1559 | while selector.get_map(): |
| 1560 | timeout = self._remaining_time(endtime) |
| 1561 | if timeout is not None and timeout < 0: |
| 1562 | raise TimeoutExpired(self.args, orig_timeout) |
| 1563 | |
| 1564 | ready = selector.select(timeout) |
| 1565 | self._check_timeout(endtime, orig_timeout) |
| 1566 | |
| 1567 | # XXX Rewrite these to use non-blocking I/O on the file |
| 1568 | # objects; they are no longer using C stdio! |
| 1569 | |
| 1570 | for key, events in ready: |
| 1571 | if key.fileobj is self.stdin: |
Gregory P. Smith | 5ca129b | 2013-12-07 19:14:59 -0800 | [diff] [blame] | 1572 | chunk = input_view[self._input_offset : |
| 1573 | self._input_offset + _PIPE_BUF] |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 1574 | try: |
| 1575 | self._input_offset += os.write(key.fd, chunk) |
Victor Stinner | a5e881d | 2015-01-14 17:07:59 +0100 | [diff] [blame] | 1576 | except BrokenPipeError: |
| 1577 | selector.unregister(key.fileobj) |
| 1578 | key.fileobj.close() |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 1579 | else: |
| 1580 | if self._input_offset >= len(self._input): |
| 1581 | selector.unregister(key.fileobj) |
| 1582 | key.fileobj.close() |
| 1583 | elif key.fileobj in (self.stdout, self.stderr): |
Gregory P. Smith | 7b83b18 | 2013-12-08 10:58:28 -0800 | [diff] [blame] | 1584 | data = os.read(key.fd, 32768) |
Charles-François Natali | 3a4586a | 2013-11-08 19:56:59 +0100 | [diff] [blame] | 1585 | if not data: |
| 1586 | selector.unregister(key.fileobj) |
| 1587 | key.fileobj.close() |
| 1588 | self._fileobj2output[key.fileobj].append(data) |
Reid Kleckner | 31aa7dd | 2011-03-14 12:02:10 -0400 | [diff] [blame] | 1589 | |
| 1590 | self.wait(timeout=self._remaining_time(endtime)) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1591 | |
| 1592 | # All data exchanged. Translate lists into strings. |
| 1593 | if stdout is not None: |
| 1594 | stdout = b''.join(stdout) |
| 1595 | if stderr is not None: |
| 1596 | stderr = b''.join(stderr) |
| 1597 | |
| 1598 | # Translate newlines, if requested. |
| 1599 | # This also turns bytes into strings. |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 1600 | if self.text_mode: |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1601 | if stdout is not None: |
| 1602 | stdout = self._translate_newlines(stdout, |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 1603 | self.stdout.encoding, |
| 1604 | self.stdout.errors) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1605 | if stderr is not None: |
| 1606 | stderr = self._translate_newlines(stderr, |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 1607 | self.stderr.encoding, |
| 1608 | self.stderr.errors) |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1609 | |
Gregory P. Smith | d06fa47 | 2009-07-04 02:46:54 +0000 | [diff] [blame] | 1610 | return (stdout, stderr) |
| 1611 | |
| 1612 | |
Andrew Svetlov | aa0dbdc | 2012-08-14 18:40:21 +0300 | [diff] [blame] | 1613 | def _save_input(self, input): |
| 1614 | # This method is called from the _communicate_with_*() methods |
| 1615 | # so that if we time out while communicating, we can continue |
| 1616 | # sending input if we retry. |
| 1617 | if self.stdin and self._input is None: |
| 1618 | self._input_offset = 0 |
| 1619 | self._input = input |
andyclegg | 7fed7bd | 2017-10-23 03:01:19 +0100 | [diff] [blame] | 1620 | if input is not None and self.text_mode: |
Steve Dower | 050acae | 2016-09-06 20:16:17 -0700 | [diff] [blame] | 1621 | self._input = self._input.encode(self.stdin.encoding, |
| 1622 | self.stdin.errors) |
Andrew Svetlov | aa0dbdc | 2012-08-14 18:40:21 +0300 | [diff] [blame] | 1623 | |
| 1624 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1625 | def send_signal(self, sig): |
Gregory P. Smith | a0c9caa | 2015-11-15 18:19:10 -0800 | [diff] [blame] | 1626 | """Send a signal to the process.""" |
| 1627 | # Skip signalling a process that we know has already died. |
| 1628 | if self.returncode is None: |
| 1629 | os.kill(self.pid, sig) |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1630 | |
| 1631 | def terminate(self): |
| 1632 | """Terminate the process with SIGTERM |
| 1633 | """ |
| 1634 | self.send_signal(signal.SIGTERM) |
| 1635 | |
| 1636 | def kill(self): |
| 1637 | """Kill the process with SIGKILL |
| 1638 | """ |
| 1639 | self.send_signal(signal.SIGKILL) |