| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
r"""Subprocesses with accessible I/O streams |
| 10 |
|
| 11 |
This module allows you to spawn processes, connect to their |
| 12 |
input/output/error pipes, and obtain their return codes. |
| 13 |
|
| 14 |
For a complete description of this module see the Python documentation. |
| 15 |
|
| 16 |
Main API |
| 17 |
======== |
| 18 |
run(...): Runs a command, waits for it to complete, then returns a |
| 19 |
CompletedProcess instance. |
| 20 |
Popen(...): A class for flexibly executing a command in a new process |
| 21 |
|
| 22 |
Constants |
| 23 |
--------- |
| 24 |
DEVNULL: Special value that indicates that os.devnull should be used |
| 25 |
PIPE: Special value that indicates a pipe should be created |
| 26 |
STDOUT: Special value that indicates that stderr should go to stdout |
| 27 |
|
| 28 |
|
| 29 |
Older API |
| 30 |
========= |
| 31 |
call(...): Runs a command, waits for it to complete, then returns |
| 32 |
the return code. |
| 33 |
check_call(...): Same as call() but raises CalledProcessError() |
| 34 |
if return code is not 0 |
| 35 |
check_output(...): Same as check_call() but returns the contents of |
| 36 |
stdout instead of a return code |
| 37 |
getoutput(...): Runs a command in the shell, waits for it to complete, |
| 38 |
then returns the output |
| 39 |
getstatusoutput(...): Runs a command in the shell, waits for it to complete, |
| 40 |
then returns a (exitcode, output) tuple |
| 41 |
""" |
| 42 |
|
| 43 |
import builtins |
| 44 |
import errno |
| 45 |
import io |
| 46 |
import locale |
| 47 |
import os |
| 48 |
import time |
| 49 |
import signal |
| 50 |
import sys |
| 51 |
import threading |
| 52 |
import warnings |
| 53 |
import contextlib |
| 54 |
from time import monotonic as _time |
| 55 |
import types |
| 56 |
|
| 57 |
try: |
| 58 |
import fcntl |
| 59 |
except ImportError: |
| 60 |
fcntl = None |
| 61 |
|
| 62 |
|
| 63 |
__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput", |
| 64 |
"getoutput", "check_output", "run", "CalledProcessError", "DEVNULL", |
| 65 |
"SubprocessError", "TimeoutExpired", "CompletedProcess"] |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
try: |
| 71 |
import msvcrt |
| 72 |
except ModuleNotFoundError: |
| 73 |
_mswindows = False |
| 74 |
else: |
| 75 |
_mswindows = True |
| 76 |
|
| 77 |
|
| 78 |
_can_fork_exec = sys.platform not in {"emscripten", "wasi"} |
| 79 |
|
| 80 |
if _mswindows: |
| 81 |
import _winapi |
| 82 |
from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, |
| 83 |
STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, |
| 84 |
STD_ERROR_HANDLE, SW_HIDE, |
| 85 |
STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW, |
| 86 |
ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, |
| 87 |
HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS, |
| 88 |
NORMAL_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS, |
| 89 |
CREATE_NO_WINDOW, DETACHED_PROCESS, |
| 90 |
CREATE_DEFAULT_ERROR_MODE, CREATE_BREAKAWAY_FROM_JOB) |
| 91 |
|
| 92 |
__all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", |
| 93 |
"STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", |
| 94 |
"STD_ERROR_HANDLE", "SW_HIDE", |
| 95 |
"STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW", |
| 96 |
"STARTUPINFO", |
| 97 |
"ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS", |
| 98 |
"HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", |
| 99 |
"NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS", |
| 100 |
"CREATE_NO_WINDOW", "DETACHED_PROCESS", |
| 101 |
"CREATE_DEFAULT_ERROR_MODE", "CREATE_BREAKAWAY_FROM_JOB"]) |
| 102 |
else: |
| 103 |
if _can_fork_exec: |
| 104 |
from _posixsubprocess import fork_exec as _fork_exec |
| 105 |
|
| 106 |
_waitpid = os.waitpid |
| 107 |
_waitstatus_to_exitcode = os.waitstatus_to_exitcode |
| 108 |
_WIFSTOPPED = os.WIFSTOPPED |
| 109 |
_WSTOPSIG = os.WSTOPSIG |
| 110 |
_WNOHANG = os.WNOHANG |
| 111 |
else: |
| 112 |
_fork_exec = None |
| 113 |
_waitpid = None |
| 114 |
_waitstatus_to_exitcode = None |
| 115 |
_WIFSTOPPED = None |
| 116 |
_WSTOPSIG = None |
| 117 |
_WNOHANG = None |
| 118 |
import select |
| 119 |
import selectors |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
class SubprocessError(Exception): pass |
| 124 |
|
| 125 |
|
| 126 |
class CalledProcessError(SubprocessError): |
| 127 |
"""Raised when run() is called with check=True and the process |
| 128 |
returns a non-zero exit status. |
| 129 |
|
| 130 |
Attributes: |
| 131 |
cmd, returncode, stdout, stderr, output |
| 132 |
""" |
| 133 |
def __init__(self, returncode, cmd, output=None, stderr=None): |
| 134 |
self.returncode = returncode |
| 135 |
self.cmd = cmd |
| 136 |
self.output = output |
| 137 |
self.stderr = stderr |
| 138 |
|
| 139 |
def __str__(self): |
| 140 |
if self.returncode and self.returncode < 0: |
| 141 |
try: |
| 142 |
return "Command '%s' died with %r." % ( |
| 143 |
self.cmd, signal.Signals(-self.returncode)) |
| 144 |
except ValueError: |
| 145 |
return "Command '%s' died with unknown signal %d." % ( |
| 146 |
self.cmd, -self.returncode) |
| 147 |
else: |
| 148 |
return "Command '%s' returned non-zero exit status %d." % ( |
| 149 |
self.cmd, self.returncode) |
| 150 |
|
| 151 |
@property |
| 152 |
def stdout(self): |
| 153 |
"""Alias for output attribute, to match stderr""" |
| 154 |
return self.output |
| 155 |
|
| 156 |
@stdout.setter |
| 157 |
def stdout(self, value): |
| 158 |
|
| 159 |
|
| 160 |
self.output = value |
| 161 |
|
| 162 |
|
| 163 |
class TimeoutExpired(SubprocessError): |
| 164 |
"""This exception is raised when the timeout expires while waiting for a |
| 165 |
child process. |
| 166 |
|
| 167 |
Attributes: |
| 168 |
cmd, output, stdout, stderr, timeout |
| 169 |
""" |
| 170 |
def __init__(self, cmd, timeout, output=None, stderr=None): |
| 171 |
self.cmd = cmd |
| 172 |
self.timeout = timeout |
| 173 |
self.output = output |
| 174 |
self.stderr = stderr |
| 175 |
|
| 176 |
def __str__(self): |
| 177 |
return ("Command '%s' timed out after %s seconds" % |
| 178 |
(self.cmd, self.timeout)) |
| 179 |
|
| 180 |
@property |
| 181 |
def stdout(self): |
| 182 |
return self.output |
| 183 |
|
| 184 |
@stdout.setter |
| 185 |
def stdout(self, value): |
| 186 |
|
| 187 |
|
| 188 |
self.output = value |
| 189 |
|
| 190 |
|
| 191 |
if _mswindows: |
| 192 |
class STARTUPINFO: |
| 193 |
def __init__(self, *, dwFlags=0, hStdInput=None, hStdOutput=None, |
| 194 |
hStdError=None, wShowWindow=0, lpAttributeList=None): |
| 195 |
self.dwFlags = dwFlags |
| 196 |
self.hStdInput = hStdInput |
| 197 |
self.hStdOutput = hStdOutput |
| 198 |
self.hStdError = hStdError |
| 199 |
self.wShowWindow = wShowWindow |
| 200 |
self.lpAttributeList = lpAttributeList or {"handle_list": []} |
| 201 |
|
| 202 |
def copy(self): |
| 203 |
attr_list = self.lpAttributeList.copy() |
| 204 |
if 'handle_list' in attr_list: |
| 205 |
attr_list['handle_list'] = list(attr_list['handle_list']) |
| 206 |
|
| 207 |
return STARTUPINFO(dwFlags=self.dwFlags, |
| 208 |
hStdInput=self.hStdInput, |
| 209 |
hStdOutput=self.hStdOutput, |
| 210 |
hStdError=self.hStdError, |
| 211 |
wShowWindow=self.wShowWindow, |
| 212 |
lpAttributeList=attr_list) |
| 213 |
|
| 214 |
|
| 215 |
class Handle(int): |
| 216 |
closed = False |
| 217 |
|
| 218 |
def Close(self, CloseHandle=_winapi.CloseHandle): |
| 219 |
if not self.closed: |
| 220 |
self.closed = True |
| 221 |
CloseHandle(self) |
| 222 |
|
| 223 |
def Detach(self): |
| 224 |
if not self.closed: |
| 225 |
self.closed = True |
| 226 |
return int(self) |
| 227 |
raise ValueError("already closed") |
| 228 |
|
| 229 |
def __repr__(self): |
| 230 |
return "%s(%d)" % (self.__class__.__name__, int(self)) |
| 231 |
|
| 232 |
__del__ = Close |
| 233 |
else: |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
_PIPE_BUF = getattr(select, 'PIPE_BUF', 512) |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
if hasattr(selectors, 'PollSelector'): |
| 243 |
_PopenSelector = selectors.PollSelector |
| 244 |
else: |
| 245 |
_PopenSelector = selectors.SelectSelector |
| 246 |
|
| 247 |
|
| 248 |
if _mswindows: |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
_active = None |
| 258 |
|
| 259 |
def _cleanup(): |
| 260 |
pass |
| 261 |
else: |
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
_active = [] |
| 267 |
|
| 268 |
def _cleanup(): |
| 269 |
if _active is None: |
| 270 |
return |
| 271 |
for inst in _active[:]: |
| 272 |
res = inst._internal_poll(_deadstate=sys.maxsize) |
| 273 |
if res is not None: |
| 274 |
try: |
| 275 |
_active.remove(inst) |
| 276 |
except ValueError: |
| 277 |
|
| 278 |
|
| 279 |
pass |
| 280 |
|
| 281 |
PIPE = -1 |
| 282 |
STDOUT = -2 |
| 283 |
DEVNULL = -3 |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
def _optim_args_from_interpreter_flags(): |
| 291 |
"""Return a list of command-line arguments reproducing the current |
| 292 |
optimization settings in sys.flags.""" |
| 293 |
args = [] |
| 294 |
value = sys.flags.optimize |
| 295 |
if value > 0: |
| 296 |
args.append('-' + 'O' * value) |
| 297 |
return args |
| 298 |
|
| 299 |
|
| 300 |
def _args_from_interpreter_flags(): |
| 301 |
"""Return a list of command-line arguments reproducing the current |
| 302 |
settings in sys.flags, sys.warnoptions and sys._xoptions.""" |
| 303 |
flag_opt_map = { |
| 304 |
'debug': 'd', |
| 305 |
|
| 306 |
|
| 307 |
'dont_write_bytecode': 'B', |
| 308 |
'no_site': 'S', |
| 309 |
'verbose': 'v', |
| 310 |
'bytes_warning': 'b', |
| 311 |
'quiet': 'q', |
| 312 |
|
| 313 |
} |
| 314 |
args = _optim_args_from_interpreter_flags() |
| 315 |
for flag, opt in flag_opt_map.items(): |
| 316 |
v = getattr(sys.flags, flag) |
| 317 |
if v > 0: |
| 318 |
args.append('-' + opt * v) |
| 319 |
|
| 320 |
if sys.flags.isolated: |
| 321 |
args.append('-I') |
| 322 |
else: |
| 323 |
if sys.flags.ignore_environment: |
| 324 |
args.append('-E') |
| 325 |
if sys.flags.no_user_site: |
| 326 |
args.append('-s') |
| 327 |
if sys.flags.safe_path: |
| 328 |
args.append('-P') |
| 329 |
|
| 330 |
|
| 331 |
warnopts = sys.warnoptions[:] |
| 332 |
xoptions = getattr(sys, '_xoptions', {}) |
| 333 |
bytes_warning = sys.flags.bytes_warning |
| 334 |
dev_mode = sys.flags.dev_mode |
| 335 |
|
| 336 |
if bytes_warning > 1: |
| 337 |
warnopts.remove("error::BytesWarning") |
| 338 |
elif bytes_warning: |
| 339 |
warnopts.remove("default::BytesWarning") |
| 340 |
if dev_mode: |
| 341 |
warnopts.remove('default') |
| 342 |
for opt in warnopts: |
| 343 |
args.append('-W' + opt) |
| 344 |
|
| 345 |
|
| 346 |
if dev_mode: |
| 347 |
args.extend(('-X', 'dev')) |
| 348 |
for opt in ('faulthandler', 'tracemalloc', 'importtime', |
| 349 |
'frozen_modules', 'showrefcount', 'utf8'): |
| 350 |
if opt in xoptions: |
| 351 |
value = xoptions[opt] |
| 352 |
if value is True: |
| 353 |
arg = opt |
| 354 |
else: |
| 355 |
arg = '%s=%s' % (opt, value) |
| 356 |
args.extend(('-X', arg)) |
| 357 |
|
| 358 |
return args |
| 359 |
|
| 360 |
|
| 361 |
def _text_encoding(): |
| 362 |
|
| 363 |
|
| 364 |
if sys.flags.warn_default_encoding: |
| 365 |
f = sys._getframe() |
| 366 |
filename = f.f_code.co_filename |
| 367 |
stacklevel = 2 |
| 368 |
while f := f.f_back: |
| 369 |
if f.f_code.co_filename != filename: |
| 370 |
break |
| 371 |
stacklevel += 1 |
| 372 |
warnings.warn("'encoding' argument not specified.", |
| 373 |
EncodingWarning, stacklevel) |
| 374 |
|
| 375 |
if sys.flags.utf8_mode: |
| 376 |
return "utf-8" |
| 377 |
else: |
| 378 |
return locale.getencoding() |
| 379 |
|
| 380 |
|
| 381 |
def call(*popenargs, timeout=None, **kwargs): |
| 382 |
"""Run command with arguments. Wait for command to complete or |
| 383 |
timeout, then return the returncode attribute. |
| 384 |
|
| 385 |
The arguments are the same as for the Popen constructor. Example: |
| 386 |
|
| 387 |
retcode = call(["ls", "-l"]) |
| 388 |
""" |
| 389 |
with Popen(*popenargs, **kwargs) as p: |
| 390 |
try: |
| 391 |
return p.wait(timeout=timeout) |
| 392 |
except: |
| 393 |
p.kill() |
| 394 |
|
| 395 |
raise |
| 396 |
|
| 397 |
|
| 398 |
def check_call(*popenargs, **kwargs): |
| 399 |
"""Run command with arguments. Wait for command to complete. If |
| 400 |
the exit code was zero then return, otherwise raise |
| 401 |
CalledProcessError. The CalledProcessError object will have the |
| 402 |
return code in the returncode attribute. |
| 403 |
|
| 404 |
The arguments are the same as for the call function. Example: |
| 405 |
|
| 406 |
check_call(["ls", "-l"]) |
| 407 |
""" |
| 408 |
retcode = call(*popenargs, **kwargs) |
| 409 |
if retcode: |
| 410 |
cmd = kwargs.get("args") |
| 411 |
if cmd is None: |
| 412 |
cmd = popenargs[0] |
| 413 |
raise CalledProcessError(retcode, cmd) |
| 414 |
return 0 |
| 415 |
|
| 416 |
|
| 417 |
def check_output(*popenargs, timeout=None, **kwargs): |
| 418 |
r"""Run command with arguments and return its output. |
| 419 |
|
| 420 |
If the exit code was non-zero it raises a CalledProcessError. The |
| 421 |
CalledProcessError object will have the return code in the returncode |
| 422 |
attribute and output in the output attribute. |
| 423 |
|
| 424 |
The arguments are the same as for the Popen constructor. Example: |
| 425 |
|
| 426 |
>>> check_output(["ls", "-l", "/dev/null"]) |
| 427 |
b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' |
| 428 |
|
| 429 |
The stdout argument is not allowed as it is used internally. |
| 430 |
To capture standard error in the result, use stderr=STDOUT. |
| 431 |
|
| 432 |
>>> check_output(["/bin/sh", "-c", |
| 433 |
... "ls -l non_existent_file ; exit 0"], |
| 434 |
... stderr=STDOUT) |
| 435 |
b'ls: non_existent_file: No such file or directory\n' |
| 436 |
|
| 437 |
There is an additional optional argument, "input", allowing you to |
| 438 |
pass a string to the subprocess's stdin. If you use this argument |
| 439 |
you may not also use the Popen constructor's "stdin" argument, as |
| 440 |
it too will be used internally. Example: |
| 441 |
|
| 442 |
>>> check_output(["sed", "-e", "s/foo/bar/"], |
| 443 |
... input=b"when in the course of fooman events\n") |
| 444 |
b'when in the course of barman events\n' |
| 445 |
|
| 446 |
By default, all communication is in bytes, and therefore any "input" |
| 447 |
should be bytes, and the return value will be bytes. If in text mode, |
| 448 |
any "input" should be a string, and the return value will be a string |
| 449 |
decoded according to locale encoding, or by "encoding" if set. Text mode |
| 450 |
is triggered by setting any of text, encoding, errors or universal_newlines. |
| 451 |
""" |
| 452 |
for kw in ('stdout', 'check'): |
| 453 |
if kw in kwargs: |
| 454 |
raise ValueError(f'{kw} argument not allowed, it will be overridden.') |
| 455 |
|
| 456 |
if 'input' in kwargs and kwargs['input'] is None: |
| 457 |
|
| 458 |
|
| 459 |
if kwargs.get('universal_newlines') or kwargs.get('text') or kwargs.get('encoding') \ |
| 460 |
or kwargs.get('errors'): |
| 461 |
empty = '' |
| 462 |
else: |
| 463 |
empty = b'' |
| 464 |
kwargs['input'] = empty |
| 465 |
|
| 466 |
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, |
| 467 |
**kwargs).stdout |
| 468 |
|
| 469 |
|
| 470 |
class CompletedProcess(object): |
| 471 |
"""A process that has finished running. |
| 472 |
|
| 473 |
This is returned by run(). |
| 474 |
|
| 475 |
Attributes: |
| 476 |
args: The list or str args passed to run(). |
| 477 |
returncode: The exit code of the process, negative for signals. |
| 478 |
stdout: The standard output (None if not captured). |
| 479 |
stderr: The standard error (None if not captured). |
| 480 |
""" |
| 481 |
def __init__(self, args, returncode, stdout=None, stderr=None): |
| 482 |
self.args = args |
| 483 |
self.returncode = returncode |
| 484 |
self.stdout = stdout |
| 485 |
self.stderr = stderr |
| 486 |
|
| 487 |
def __repr__(self): |
| 488 |
args = ['args={!r}'.format(self.args), |
| 489 |
'returncode={!r}'.format(self.returncode)] |
| 490 |
if self.stdout is not None: |
| 491 |
args.append('stdout={!r}'.format(self.stdout)) |
| 492 |
if self.stderr is not None: |
| 493 |
args.append('stderr={!r}'.format(self.stderr)) |
| 494 |
return "{}({})".format(type(self).__name__, ', '.join(args)) |
| 495 |
|
| 496 |
__class_getitem__ = classmethod(types.GenericAlias) |
| 497 |
|
| 498 |
|
| 499 |
def check_returncode(self): |
| 500 |
"""Raise CalledProcessError if the exit code is non-zero.""" |
| 501 |
if self.returncode: |
| 502 |
raise CalledProcessError(self.returncode, self.args, self.stdout, |
| 503 |
self.stderr) |
| 504 |
|
| 505 |
|
| 506 |
def run(*popenargs, |
| 507 |
input=None, capture_output=False, timeout=None, check=False, **kwargs): |
| 508 |
"""Run command with arguments and return a CompletedProcess instance. |
| 509 |
|
| 510 |
The returned instance will have attributes args, returncode, stdout and |
| 511 |
stderr. By default, stdout and stderr are not captured, and those attributes |
| 512 |
will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them, |
| 513 |
or pass capture_output=True to capture both. |
| 514 |
|
| 515 |
If check is True and the exit code was non-zero, it raises a |
| 516 |
CalledProcessError. The CalledProcessError object will have the return code |
| 517 |
in the returncode attribute, and output & stderr attributes if those streams |
| 518 |
were captured. |
| 519 |
|
| 520 |
If timeout is given, and the process takes too long, a TimeoutExpired |
| 521 |
exception will be raised. |
| 522 |
|
| 523 |
There is an optional argument "input", allowing you to |
| 524 |
pass bytes or a string to the subprocess's stdin. If you use this argument |
| 525 |
you may not also use the Popen constructor's "stdin" argument, as |
| 526 |
it will be used internally. |
| 527 |
|
| 528 |
By default, all communication is in bytes, and therefore any "input" should |
| 529 |
be bytes, and the stdout and stderr will be bytes. If in text mode, any |
| 530 |
"input" should be a string, and stdout and stderr will be strings decoded |
| 531 |
according to locale encoding, or by "encoding" if set. Text mode is |
| 532 |
triggered by setting any of text, encoding, errors or universal_newlines. |
| 533 |
|
| 534 |
The other arguments are the same as for the Popen constructor. |
| 535 |
""" |
| 536 |
if input is not None: |
| 537 |
if kwargs.get('stdin') is not None: |
| 538 |
raise ValueError('stdin and input arguments may not both be used.') |
| 539 |
kwargs['stdin'] = PIPE |
| 540 |
|
| 541 |
if capture_output: |
| 542 |
if kwargs.get('stdout') is not None or kwargs.get('stderr') is not None: |
| 543 |
raise ValueError('stdout and stderr arguments may not be used ' |
| 544 |
'with capture_output.') |
| 545 |
kwargs['stdout'] = PIPE |
| 546 |
kwargs['stderr'] = PIPE |
| 547 |
|
| 548 |
with Popen(*popenargs, **kwargs) as process: |
| 549 |
try: |
| 550 |
stdout, stderr = process.communicate(input, timeout=timeout) |
| 551 |
except TimeoutExpired as exc: |
| 552 |
process.kill() |
| 553 |
if _mswindows: |
| 554 |
|
| 555 |
|
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
exc.stdout, exc.stderr = process.communicate() |
| 560 |
else: |
| 561 |
|
| 562 |
|
| 563 |
process.wait() |
| 564 |
raise |
| 565 |
except: |
| 566 |
process.kill() |
| 567 |
|
| 568 |
raise |
| 569 |
retcode = process.poll() |
| 570 |
if check and retcode: |
| 571 |
raise CalledProcessError(retcode, process.args, |
| 572 |
output=stdout, stderr=stderr) |
| 573 |
return CompletedProcess(process.args, retcode, stdout, stderr) |
| 574 |
|
| 575 |
|
| 576 |
def list2cmdline(seq): |
| 577 |
""" |
| 578 |
Translate a sequence of arguments into a command line |
| 579 |
string, using the same rules as the MS C runtime: |
| 580 |
|
| 581 |
1) Arguments are delimited by white space, which is either a |
| 582 |
space or a tab. |
| 583 |
|
| 584 |
2) A string surrounded by double quotation marks is |
| 585 |
interpreted as a single argument, regardless of white space |
| 586 |
contained within. A quoted string can be embedded in an |
| 587 |
argument. |
| 588 |
|
| 589 |
3) A double quotation mark preceded by a backslash is |
| 590 |
interpreted as a literal double quotation mark. |
| 591 |
|
| 592 |
4) Backslashes are interpreted literally, unless they |
| 593 |
immediately precede a double quotation mark. |
| 594 |
|
| 595 |
5) If backslashes immediately precede a double quotation mark, |
| 596 |
every pair of backslashes is interpreted as a literal |
| 597 |
backslash. If the number of backslashes is odd, the last |
| 598 |
backslash escapes the next double quotation mark as |
| 599 |
described in rule 3. |
| 600 |
""" |
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
result = [] |
| 607 |
needquote = False |
| 608 |
for arg in map(os.fsdecode, seq): |
| 609 |
bs_buf = [] |
| 610 |
|
| 611 |
|
| 612 |
if result: |
| 613 |
result.append(' ') |
| 614 |
|
| 615 |
needquote = (" " in arg) or ("\t" in arg) or not arg |
| 616 |
if needquote: |
| 617 |
result.append('"') |
| 618 |
|
| 619 |
for c in arg: |
| 620 |
if c == '\\': |
| 621 |
|
| 622 |
bs_buf.append(c) |
| 623 |
elif c == '"': |
| 624 |
|
| 625 |
result.append('\\' * len(bs_buf)*2) |
| 626 |
bs_buf = [] |
| 627 |
result.append('\\"') |
| 628 |
else: |
| 629 |
|
| 630 |
if bs_buf: |
| 631 |
result.extend(bs_buf) |
| 632 |
bs_buf = [] |
| 633 |
result.append(c) |
| 634 |
|
| 635 |
|
| 636 |
if bs_buf: |
| 637 |
result.extend(bs_buf) |
| 638 |
|
| 639 |
if needquote: |
| 640 |
result.extend(bs_buf) |
| 641 |
result.append('"') |
| 642 |
|
| 643 |
return ''.join(result) |
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
|
| 648 |
|
| 649 |
def getstatusoutput(cmd, *, encoding=None, errors=None): |
| 650 |
"""Return (exitcode, output) of executing cmd in a shell. |
| 651 |
|
| 652 |
Execute the string 'cmd' in a shell with 'check_output' and |
| 653 |
return a 2-tuple (status, output). The locale encoding is used |
| 654 |
to decode the output and process newlines. |
| 655 |
|
| 656 |
A trailing newline is stripped from the output. |
| 657 |
The exit status for the command can be interpreted |
| 658 |
according to the rules for the function 'wait'. Example: |
| 659 |
|
| 660 |
>>> import subprocess |
| 661 |
>>> subprocess.getstatusoutput('ls /bin/ls') |
| 662 |
(0, '/bin/ls') |
| 663 |
>>> subprocess.getstatusoutput('cat /bin/junk') |
| 664 |
(1, 'cat: /bin/junk: No such file or directory') |
| 665 |
>>> subprocess.getstatusoutput('/bin/junk') |
| 666 |
(127, 'sh: /bin/junk: not found') |
| 667 |
>>> subprocess.getstatusoutput('/bin/kill $$') |
| 668 |
(-15, '') |
| 669 |
""" |
| 670 |
try: |
| 671 |
data = check_output(cmd, shell=True, text=True, stderr=STDOUT, |
| 672 |
encoding=encoding, errors=errors) |
| 673 |
exitcode = 0 |
| 674 |
except CalledProcessError as ex: |
| 675 |
data = ex.output |
| 676 |
exitcode = ex.returncode |
| 677 |
if data[-1:] == '\n': |
| 678 |
data = data[:-1] |
| 679 |
return exitcode, data |
| 680 |
|
| 681 |
def getoutput(cmd, *, encoding=None, errors=None): |
| 682 |
"""Return output (stdout or stderr) of executing cmd in a shell. |
| 683 |
|
| 684 |
Like getstatusoutput(), except the exit status is ignored and the return |
| 685 |
value is a string containing the command's output. Example: |
| 686 |
|
| 687 |
>>> import subprocess |
| 688 |
>>> subprocess.getoutput('ls /bin/ls') |
| 689 |
'/bin/ls' |
| 690 |
""" |
| 691 |
return getstatusoutput(cmd, encoding=encoding, errors=errors)[1] |
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
def _use_posix_spawn(): |
| 696 |
"""Check if posix_spawn() can be used for subprocess. |
| 697 |
|
| 698 |
subprocess requires a posix_spawn() implementation that properly reports |
| 699 |
errors to the parent process, & sets errno on the following failures: |
| 700 |
|
| 701 |
* Process attribute actions failed. |
| 702 |
* File actions failed. |
| 703 |
* exec() failed. |
| 704 |
|
| 705 |
Prefer an implementation which can use vfork() in some cases for best |
| 706 |
performance. |
| 707 |
""" |
| 708 |
if _mswindows or not hasattr(os, 'posix_spawn'): |
| 709 |
|
| 710 |
return False |
| 711 |
|
| 712 |
if sys.platform in ('darwin', 'sunos5'): |
| 713 |
|
| 714 |
|
| 715 |
return True |
| 716 |
|
| 717 |
|
| 718 |
try: |
| 719 |
ver = os.confstr('CS_GNU_LIBC_VERSION') |
| 720 |
|
| 721 |
parts = ver.split(maxsplit=1) |
| 722 |
if len(parts) != 2: |
| 723 |
|
| 724 |
raise ValueError |
| 725 |
libc = parts[0] |
| 726 |
version = tuple(map(int, parts[1].split('.'))) |
| 727 |
|
| 728 |
if sys.platform == 'linux' and libc == 'glibc' and version >= (2, 24): |
| 729 |
|
| 730 |
|
| 731 |
return True |
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
except (AttributeError, ValueError, OSError): |
| 736 |
|
| 737 |
pass |
| 738 |
|
| 739 |
|
| 740 |
return False |
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
_USE_POSIX_SPAWN = _use_posix_spawn() |
| 746 |
_USE_VFORK = True |
| 747 |
|
| 748 |
|
| 749 |
class Popen: |
| 750 |
""" Execute a child program in a new process. |
| 751 |
|
| 752 |
For a complete description of the arguments see the Python documentation. |
| 753 |
|
| 754 |
Arguments: |
| 755 |
args: A string, or a sequence of program arguments. |
| 756 |
|
| 757 |
bufsize: supplied as the buffering argument to the open() function when |
| 758 |
creating the stdin/stdout/stderr pipe file objects |
| 759 |
|
| 760 |
executable: A replacement program to execute. |
| 761 |
|
| 762 |
stdin, stdout and stderr: These specify the executed programs' standard |
| 763 |
input, standard output and standard error file handles, respectively. |
| 764 |
|
| 765 |
preexec_fn: (POSIX only) An object to be called in the child process |
| 766 |
just before the child is executed. |
| 767 |
|
| 768 |
close_fds: Controls closing or inheriting of file descriptors. |
| 769 |
|
| 770 |
shell: If true, the command will be executed through the shell. |
| 771 |
|
| 772 |
cwd: Sets the current directory before the child is executed. |
| 773 |
|
| 774 |
env: Defines the environment variables for the new process. |
| 775 |
|
| 776 |
text: If true, decode stdin, stdout and stderr using the given encoding |
| 777 |
(if set) or the system default otherwise. |
| 778 |
|
| 779 |
universal_newlines: Alias of text, provided for backwards compatibility. |
| 780 |
|
| 781 |
startupinfo and creationflags (Windows only) |
| 782 |
|
| 783 |
restore_signals (POSIX only) |
| 784 |
|
| 785 |
start_new_session (POSIX only) |
| 786 |
|
| 787 |
process_group (POSIX only) |
| 788 |
|
| 789 |
group (POSIX only) |
| 790 |
|
| 791 |
extra_groups (POSIX only) |
| 792 |
|
| 793 |
user (POSIX only) |
| 794 |
|
| 795 |
umask (POSIX only) |
| 796 |
|
| 797 |
pass_fds (POSIX only) |
| 798 |
|
| 799 |
encoding and errors: Text mode encoding and error handling to use for |
| 800 |
file objects stdin, stdout and stderr. |
| 801 |
|
| 802 |
Attributes: |
| 803 |
stdin, stdout, stderr, pid, returncode |
| 804 |
""" |
| 805 |
_child_created = False |
| 806 |
|
| 807 |
def __init__(self, args, bufsize=-1, executable=None, |
| 808 |
stdin=None, stdout=None, stderr=None, |
| 809 |
preexec_fn=None, close_fds=True, |
| 810 |
shell=False, cwd=None, env=None, universal_newlines=None, |
| 811 |
startupinfo=None, creationflags=0, |
| 812 |
restore_signals=True, start_new_session=False, |
| 813 |
pass_fds=(), *, user=None, group=None, extra_groups=None, |
| 814 |
encoding=None, errors=None, text=None, umask=-1, pipesize=-1, |
| 815 |
process_group=None): |
| 816 |
"""Create new Popen instance.""" |
| 817 |
if not _can_fork_exec: |
| 818 |
raise OSError( |
| 819 |
errno.ENOTSUP, f"{sys.platform} does not support processes." |
| 820 |
) |
| 821 |
|
| 822 |
_cleanup() |
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
self._waitpid_lock = threading.Lock() |
| 829 |
|
| 830 |
self._input = None |
| 831 |
self._communication_started = False |
| 832 |
if bufsize is None: |
| 833 |
bufsize = -1 |
| 834 |
if not isinstance(bufsize, int): |
| 835 |
raise TypeError("bufsize must be an integer") |
| 836 |
|
| 837 |
if pipesize is None: |
| 838 |
pipesize = -1 |
| 839 |
if not isinstance(pipesize, int): |
| 840 |
raise TypeError("pipesize must be an integer") |
| 841 |
|
| 842 |
if _mswindows: |
| 843 |
if preexec_fn is not None: |
| 844 |
raise ValueError("preexec_fn is not supported on Windows " |
| 845 |
"platforms") |
| 846 |
else: |
| 847 |
|
| 848 |
if pass_fds and not close_fds: |
| 849 |
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning) |
| 850 |
close_fds = True |
| 851 |
if startupinfo is not None: |
| 852 |
raise ValueError("startupinfo is only supported on Windows " |
| 853 |
"platforms") |
| 854 |
if creationflags != 0: |
| 855 |
raise ValueError("creationflags is only supported on Windows " |
| 856 |
"platforms") |
| 857 |
|
| 858 |
self.args = args |
| 859 |
self.stdin = None |
| 860 |
self.stdout = None |
| 861 |
self.stderr = None |
| 862 |
self.pid = None |
| 863 |
self.returncode = None |
| 864 |
self.encoding = encoding |
| 865 |
self.errors = errors |
| 866 |
self.pipesize = pipesize |
| 867 |
|
| 868 |
|
| 869 |
if (text is not None and universal_newlines is not None |
| 870 |
and bool(universal_newlines) != bool(text)): |
| 871 |
raise SubprocessError('Cannot disambiguate when both text ' |
| 872 |
'and universal_newlines are supplied but ' |
| 873 |
'different. Pass one or the other.') |
| 874 |
|
| 875 |
self.text_mode = encoding or errors or text or universal_newlines |
| 876 |
if self.text_mode and encoding is None: |
| 877 |
self.encoding = encoding = _text_encoding() |
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
self._sigint_wait_secs = 0.25 |
| 883 |
|
| 884 |
self._closed_child_pipe_fds = False |
| 885 |
|
| 886 |
if self.text_mode: |
| 887 |
if bufsize == 1: |
| 888 |
line_buffering = True |
| 889 |
|
| 890 |
|
| 891 |
bufsize = -1 |
| 892 |
else: |
| 893 |
line_buffering = False |
| 894 |
|
| 895 |
if process_group is None: |
| 896 |
process_group = -1 |
| 897 |
|
| 898 |
gid = None |
| 899 |
if group is not None: |
| 900 |
if not hasattr(os, 'setregid'): |
| 901 |
raise ValueError("The 'group' parameter is not supported on the " |
| 902 |
"current platform") |
| 903 |
|
| 904 |
elif isinstance(group, str): |
| 905 |
try: |
| 906 |
import grp |
| 907 |
except ImportError: |
| 908 |
raise ValueError("The group parameter cannot be a string " |
| 909 |
"on systems without the grp module") |
| 910 |
|
| 911 |
gid = grp.getgrnam(group).gr_gid |
| 912 |
elif isinstance(group, int): |
| 913 |
gid = group |
| 914 |
else: |
| 915 |
raise TypeError("Group must be a string or an integer, not {}" |
| 916 |
.format(type(group))) |
| 917 |
|
| 918 |
if gid < 0: |
| 919 |
raise ValueError(f"Group ID cannot be negative, got {gid}") |
| 920 |
|
| 921 |
gids = None |
| 922 |
if extra_groups is not None: |
| 923 |
if not hasattr(os, 'setgroups'): |
| 924 |
raise ValueError("The 'extra_groups' parameter is not " |
| 925 |
"supported on the current platform") |
| 926 |
|
| 927 |
elif isinstance(extra_groups, str): |
| 928 |
raise ValueError("Groups must be a list, not a string") |
| 929 |
|
| 930 |
gids = [] |
| 931 |
for extra_group in extra_groups: |
| 932 |
if isinstance(extra_group, str): |
| 933 |
try: |
| 934 |
import grp |
| 935 |
except ImportError: |
| 936 |
raise ValueError("Items in extra_groups cannot be " |
| 937 |
"strings on systems without the " |
| 938 |
"grp module") |
| 939 |
|
| 940 |
gids.append(grp.getgrnam(extra_group).gr_gid) |
| 941 |
elif isinstance(extra_group, int): |
| 942 |
gids.append(extra_group) |
| 943 |
else: |
| 944 |
raise TypeError("Items in extra_groups must be a string " |
| 945 |
"or integer, not {}" |
| 946 |
.format(type(extra_group))) |
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
for gid_check in gids: |
| 951 |
if gid_check < 0: |
| 952 |
raise ValueError(f"Group ID cannot be negative, got {gid_check}") |
| 953 |
|
| 954 |
uid = None |
| 955 |
if user is not None: |
| 956 |
if not hasattr(os, 'setreuid'): |
| 957 |
raise ValueError("The 'user' parameter is not supported on " |
| 958 |
"the current platform") |
| 959 |
|
| 960 |
elif isinstance(user, str): |
| 961 |
try: |
| 962 |
import pwd |
| 963 |
except ImportError: |
| 964 |
raise ValueError("The user parameter cannot be a string " |
| 965 |
"on systems without the pwd module") |
| 966 |
uid = pwd.getpwnam(user).pw_uid |
| 967 |
elif isinstance(user, int): |
| 968 |
uid = user |
| 969 |
else: |
| 970 |
raise TypeError("User must be a string or an integer") |
| 971 |
|
| 972 |
if uid < 0: |
| 973 |
raise ValueError(f"User ID cannot be negative, got {uid}") |
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
|
| 985 |
|
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
(p2cread, p2cwrite, |
| 991 |
c2pread, c2pwrite, |
| 992 |
errread, errwrite) = self._get_handles(stdin, stdout, stderr) |
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
if _mswindows: |
| 1001 |
if p2cwrite != -1: |
| 1002 |
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) |
| 1003 |
if c2pread != -1: |
| 1004 |
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) |
| 1005 |
if errread != -1: |
| 1006 |
errread = msvcrt.open_osfhandle(errread.Detach(), 0) |
| 1007 |
|
| 1008 |
try: |
| 1009 |
if p2cwrite != -1: |
| 1010 |
self.stdin = io.open(p2cwrite, 'wb', bufsize) |
| 1011 |
if self.text_mode: |
| 1012 |
self.stdin = io.TextIOWrapper(self.stdin, write_through=True, |
| 1013 |
line_buffering=line_buffering, |
| 1014 |
encoding=encoding, errors=errors) |
| 1015 |
if c2pread != -1: |
| 1016 |
self.stdout = io.open(c2pread, 'rb', bufsize) |
| 1017 |
if self.text_mode: |
| 1018 |
self.stdout = io.TextIOWrapper(self.stdout, |
| 1019 |
encoding=encoding, errors=errors) |
| 1020 |
if errread != -1: |
| 1021 |
self.stderr = io.open(errread, 'rb', bufsize) |
| 1022 |
if self.text_mode: |
| 1023 |
self.stderr = io.TextIOWrapper(self.stderr, |
| 1024 |
encoding=encoding, errors=errors) |
| 1025 |
|
| 1026 |
self._execute_child(args, executable, preexec_fn, close_fds, |
| 1027 |
pass_fds, cwd, env, |
| 1028 |
startupinfo, creationflags, shell, |
| 1029 |
p2cread, p2cwrite, |
| 1030 |
c2pread, c2pwrite, |
| 1031 |
errread, errwrite, |
| 1032 |
restore_signals, |
| 1033 |
gid, gids, uid, umask, |
| 1034 |
start_new_session, process_group) |
| 1035 |
except: |
| 1036 |
|
| 1037 |
for f in filter(None, (self.stdin, self.stdout, self.stderr)): |
| 1038 |
try: |
| 1039 |
f.close() |
| 1040 |
except OSError: |
| 1041 |
pass |
| 1042 |
|
| 1043 |
if not self._closed_child_pipe_fds: |
| 1044 |
to_close = [] |
| 1045 |
if stdin == PIPE: |
| 1046 |
to_close.append(p2cread) |
| 1047 |
if stdout == PIPE: |
| 1048 |
to_close.append(c2pwrite) |
| 1049 |
if stderr == PIPE: |
| 1050 |
to_close.append(errwrite) |
| 1051 |
if hasattr(self, '_devnull'): |
| 1052 |
to_close.append(self._devnull) |
| 1053 |
for fd in to_close: |
| 1054 |
try: |
| 1055 |
if _mswindows and isinstance(fd, Handle): |
| 1056 |
fd.Close() |
| 1057 |
else: |
| 1058 |
os.close(fd) |
| 1059 |
except OSError: |
| 1060 |
pass |
| 1061 |
|
| 1062 |
raise |
| 1063 |
|
| 1064 |
def __repr__(self): |
| 1065 |
obj_repr = ( |
| 1066 |
f"<{self.__class__.__name__}: " |
| 1067 |
f"returncode: {self.returncode} args: {self.args!r}>" |
| 1068 |
) |
| 1069 |
if len(obj_repr) > 80: |
| 1070 |
obj_repr = obj_repr[:76] + "...>" |
| 1071 |
return obj_repr |
| 1072 |
|
| 1073 |
__class_getitem__ = classmethod(types.GenericAlias) |
| 1074 |
|
| 1075 |
@property |
| 1076 |
def universal_newlines(self): |
| 1077 |
|
| 1078 |
|
| 1079 |
return self.text_mode |
| 1080 |
|
| 1081 |
@universal_newlines.setter |
| 1082 |
def universal_newlines(self, universal_newlines): |
| 1083 |
self.text_mode = bool(universal_newlines) |
| 1084 |
|
| 1085 |
def _translate_newlines(self, data, encoding, errors): |
| 1086 |
data = data.decode(encoding, errors) |
| 1087 |
return data.replace("\r\n", "\n").replace("\r", "\n") |
| 1088 |
|
| 1089 |
def __enter__(self): |
| 1090 |
return self |
| 1091 |
|
| 1092 |
def __exit__(self, exc_type, value, traceback): |
| 1093 |
if self.stdout: |
| 1094 |
self.stdout.close() |
| 1095 |
if self.stderr: |
| 1096 |
self.stderr.close() |
| 1097 |
try: |
| 1098 |
if self.stdin: |
| 1099 |
self.stdin.close() |
| 1100 |
finally: |
| 1101 |
if exc_type == KeyboardInterrupt: |
| 1102 |
|
| 1103 |
|
| 1104 |
|
| 1105 |
|
| 1106 |
|
| 1107 |
|
| 1108 |
|
| 1109 |
if self._sigint_wait_secs > 0: |
| 1110 |
try: |
| 1111 |
self._wait(timeout=self._sigint_wait_secs) |
| 1112 |
except TimeoutExpired: |
| 1113 |
pass |
| 1114 |
self._sigint_wait_secs = 0 |
| 1115 |
return |
| 1116 |
|
| 1117 |
|
| 1118 |
self.wait() |
| 1119 |
|
| 1120 |
def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn): |
| 1121 |
if not self._child_created: |
| 1122 |
|
| 1123 |
return |
| 1124 |
if self.returncode is None: |
| 1125 |
|
| 1126 |
|
| 1127 |
_warn("subprocess %s is still running" % self.pid, |
| 1128 |
ResourceWarning, source=self) |
| 1129 |
|
| 1130 |
self._internal_poll(_deadstate=_maxsize) |
| 1131 |
if self.returncode is None and _active is not None: |
| 1132 |
|
| 1133 |
_active.append(self) |
| 1134 |
|
| 1135 |
def _get_devnull(self): |
| 1136 |
if not hasattr(self, '_devnull'): |
| 1137 |
self._devnull = os.open(os.devnull, os.O_RDWR) |
| 1138 |
return self._devnull |
| 1139 |
|
| 1140 |
def _stdin_write(self, input): |
| 1141 |
if input: |
| 1142 |
try: |
| 1143 |
self.stdin.write(input) |
| 1144 |
except BrokenPipeError: |
| 1145 |
pass |
| 1146 |
except OSError as exc: |
| 1147 |
if exc.errno == errno.EINVAL: |
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
pass |
| 1152 |
else: |
| 1153 |
raise |
| 1154 |
|
| 1155 |
try: |
| 1156 |
self.stdin.close() |
| 1157 |
except BrokenPipeError: |
| 1158 |
pass |
| 1159 |
except OSError as exc: |
| 1160 |
if exc.errno == errno.EINVAL: |
| 1161 |
pass |
| 1162 |
else: |
| 1163 |
raise |
| 1164 |
|
| 1165 |
def communicate(self, input=None, timeout=None): |
| 1166 |
"""Interact with process: Send data to stdin and close it. |
| 1167 |
Read data from stdout and stderr, until end-of-file is |
| 1168 |
reached. Wait for process to terminate. |
| 1169 |
|
| 1170 |
The optional "input" argument should be data to be sent to the |
| 1171 |
child process, or None, if no data should be sent to the child. |
| 1172 |
communicate() returns a tuple (stdout, stderr). |
| 1173 |
|
| 1174 |
By default, all communication is in bytes, and therefore any |
| 1175 |
"input" should be bytes, and the (stdout, stderr) will be bytes. |
| 1176 |
If in text mode (indicated by self.text_mode), any "input" should |
| 1177 |
be a string, and (stdout, stderr) will be strings decoded |
| 1178 |
according to locale encoding, or by "encoding" if set. Text mode |
| 1179 |
is triggered by setting any of text, encoding, errors or |
| 1180 |
universal_newlines. |
| 1181 |
""" |
| 1182 |
|
| 1183 |
if self._communication_started and input: |
| 1184 |
raise ValueError("Cannot send input after starting communication") |
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
|
| 1189 |
if (timeout is None and not self._communication_started and |
| 1190 |
[self.stdin, self.stdout, self.stderr].count(None) >= 2): |
| 1191 |
stdout = None |
| 1192 |
stderr = None |
| 1193 |
if self.stdin: |
| 1194 |
self._stdin_write(input) |
| 1195 |
elif self.stdout: |
| 1196 |
stdout = self.stdout.read() |
| 1197 |
self.stdout.close() |
| 1198 |
elif self.stderr: |
| 1199 |
stderr = self.stderr.read() |
| 1200 |
self.stderr.close() |
| 1201 |
self.wait() |
| 1202 |
else: |
| 1203 |
if timeout is not None: |
| 1204 |
endtime = _time() + timeout |
| 1205 |
else: |
| 1206 |
endtime = None |
| 1207 |
|
| 1208 |
try: |
| 1209 |
stdout, stderr = self._communicate(input, endtime, timeout) |
| 1210 |
except KeyboardInterrupt: |
| 1211 |
|
| 1212 |
|
| 1213 |
if timeout is not None: |
| 1214 |
sigint_timeout = min(self._sigint_wait_secs, |
| 1215 |
self._remaining_time(endtime)) |
| 1216 |
else: |
| 1217 |
sigint_timeout = self._sigint_wait_secs |
| 1218 |
self._sigint_wait_secs = 0 |
| 1219 |
try: |
| 1220 |
self._wait(timeout=sigint_timeout) |
| 1221 |
except TimeoutExpired: |
| 1222 |
pass |
| 1223 |
raise |
| 1224 |
|
| 1225 |
finally: |
| 1226 |
self._communication_started = True |
| 1227 |
|
| 1228 |
sts = self.wait(timeout=self._remaining_time(endtime)) |
| 1229 |
|
| 1230 |
return (stdout, stderr) |
| 1231 |
|
| 1232 |
|
| 1233 |
def poll(self): |
| 1234 |
"""Check if child process has terminated. Set and return returncode |
| 1235 |
attribute.""" |
| 1236 |
return self._internal_poll() |
| 1237 |
|
| 1238 |
|
| 1239 |
def _remaining_time(self, endtime): |
| 1240 |
"""Convenience for _communicate when computing timeouts.""" |
| 1241 |
if endtime is None: |
| 1242 |
return None |
| 1243 |
else: |
| 1244 |
return endtime - _time() |
| 1245 |
|
| 1246 |
|
| 1247 |
def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq, |
| 1248 |
skip_check_and_raise=False): |
| 1249 |
"""Convenience for checking if a timeout has expired.""" |
| 1250 |
if endtime is None: |
| 1251 |
return |
| 1252 |
if skip_check_and_raise or _time() > endtime: |
| 1253 |
raise TimeoutExpired( |
| 1254 |
self.args, orig_timeout, |
| 1255 |
output=b''.join(stdout_seq) if stdout_seq else None, |
| 1256 |
stderr=b''.join(stderr_seq) if stderr_seq else None) |
| 1257 |
|
| 1258 |
|
| 1259 |
def wait(self, timeout=None): |
| 1260 |
"""Wait for child process to terminate; returns self.returncode.""" |
| 1261 |
if timeout is not None: |
| 1262 |
endtime = _time() + timeout |
| 1263 |
try: |
| 1264 |
return self._wait(timeout=timeout) |
| 1265 |
except KeyboardInterrupt: |
| 1266 |
|
| 1267 |
|
| 1268 |
|
| 1269 |
|
| 1270 |
if timeout is not None: |
| 1271 |
sigint_timeout = min(self._sigint_wait_secs, |
| 1272 |
self._remaining_time(endtime)) |
| 1273 |
else: |
| 1274 |
sigint_timeout = self._sigint_wait_secs |
| 1275 |
self._sigint_wait_secs = 0 |
| 1276 |
try: |
| 1277 |
self._wait(timeout=sigint_timeout) |
| 1278 |
except TimeoutExpired: |
| 1279 |
pass |
| 1280 |
raise |
| 1281 |
|
| 1282 |
def _close_pipe_fds(self, |
| 1283 |
p2cread, p2cwrite, |
| 1284 |
c2pread, c2pwrite, |
| 1285 |
errread, errwrite): |
| 1286 |
|
| 1287 |
devnull_fd = getattr(self, '_devnull', None) |
| 1288 |
|
| 1289 |
with contextlib.ExitStack() as stack: |
| 1290 |
if _mswindows: |
| 1291 |
if p2cread != -1: |
| 1292 |
stack.callback(p2cread.Close) |
| 1293 |
if c2pwrite != -1: |
| 1294 |
stack.callback(c2pwrite.Close) |
| 1295 |
if errwrite != -1: |
| 1296 |
stack.callback(errwrite.Close) |
| 1297 |
else: |
| 1298 |
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: |
| 1299 |
stack.callback(os.close, p2cread) |
| 1300 |
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: |
| 1301 |
stack.callback(os.close, c2pwrite) |
| 1302 |
if errwrite != -1 and errread != -1 and errwrite != devnull_fd: |
| 1303 |
stack.callback(os.close, errwrite) |
| 1304 |
|
| 1305 |
if devnull_fd is not None: |
| 1306 |
stack.callback(os.close, devnull_fd) |
| 1307 |
|
| 1308 |
|
| 1309 |
self._closed_child_pipe_fds = True |
| 1310 |
|
| 1311 |
@contextlib.contextmanager |
| 1312 |
def _on_error_fd_closer(self): |
| 1313 |
"""Helper to ensure file descriptors opened in _get_handles are closed""" |
| 1314 |
to_close = [] |
| 1315 |
try: |
| 1316 |
yield to_close |
| 1317 |
except: |
| 1318 |
if hasattr(self, '_devnull'): |
| 1319 |
to_close.append(self._devnull) |
| 1320 |
del self._devnull |
| 1321 |
for fd in to_close: |
| 1322 |
try: |
| 1323 |
if _mswindows and isinstance(fd, Handle): |
| 1324 |
fd.Close() |
| 1325 |
else: |
| 1326 |
os.close(fd) |
| 1327 |
except OSError: |
| 1328 |
pass |
| 1329 |
raise |
| 1330 |
|
| 1331 |
if _mswindows: |
| 1332 |
|
| 1333 |
|
| 1334 |
|
| 1335 |
def _get_handles(self, stdin, stdout, stderr): |
| 1336 |
"""Construct and return tuple with IO objects: |
| 1337 |
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 1338 |
""" |
| 1339 |
if stdin is None and stdout is None and stderr is None: |
| 1340 |
return (-1, -1, -1, -1, -1, -1) |
| 1341 |
|
| 1342 |
p2cread, p2cwrite = -1, -1 |
| 1343 |
c2pread, c2pwrite = -1, -1 |
| 1344 |
errread, errwrite = -1, -1 |
| 1345 |
|
| 1346 |
ispread = False |
| 1347 |
with self._on_error_fd_closer() as err_close_fds: |
| 1348 |
if stdin is None: |
| 1349 |
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) |
| 1350 |
if p2cread is None: |
| 1351 |
p2cread, _ = _winapi.CreatePipe(None, 0) |
| 1352 |
p2cread = Handle(p2cread) |
| 1353 |
err_close_fds.append(p2cread) |
| 1354 |
_winapi.CloseHandle(_) |
| 1355 |
ispread = True |
| 1356 |
elif stdin == PIPE: |
| 1357 |
p2cread, p2cwrite = _winapi.CreatePipe(None, 0) |
| 1358 |
p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) |
| 1359 |
err_close_fds.extend((p2cread, p2cwrite)) |
| 1360 |
ispread = True |
| 1361 |
elif stdin == DEVNULL: |
| 1362 |
p2cread = msvcrt.get_osfhandle(self._get_devnull()) |
| 1363 |
elif isinstance(stdin, int): |
| 1364 |
p2cread = msvcrt.get_osfhandle(stdin) |
| 1365 |
else: |
| 1366 |
|
| 1367 |
p2cread = msvcrt.get_osfhandle(stdin.fileno()) |
| 1368 |
p2cread = self._make_inheritable(p2cread, ispread) |
| 1369 |
|
| 1370 |
ispwrite = False |
| 1371 |
if stdout is None: |
| 1372 |
c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE) |
| 1373 |
if c2pwrite is None: |
| 1374 |
_, c2pwrite = _winapi.CreatePipe(None, 0) |
| 1375 |
c2pwrite = Handle(c2pwrite) |
| 1376 |
err_close_fds.append(c2pwrite) |
| 1377 |
_winapi.CloseHandle(_) |
| 1378 |
ispwrite = True |
| 1379 |
elif stdout == PIPE: |
| 1380 |
c2pread, c2pwrite = _winapi.CreatePipe(None, 0) |
| 1381 |
c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) |
| 1382 |
err_close_fds.extend((c2pread, c2pwrite)) |
| 1383 |
ispwrite = True |
| 1384 |
elif stdout == DEVNULL: |
| 1385 |
c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) |
| 1386 |
elif isinstance(stdout, int): |
| 1387 |
c2pwrite = msvcrt.get_osfhandle(stdout) |
| 1388 |
else: |
| 1389 |
|
| 1390 |
c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) |
| 1391 |
c2pwrite = self._make_inheritable(c2pwrite, ispwrite) |
| 1392 |
|
| 1393 |
ispwrite = False |
| 1394 |
if stderr is None: |
| 1395 |
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) |
| 1396 |
if errwrite is None: |
| 1397 |
_, errwrite = _winapi.CreatePipe(None, 0) |
| 1398 |
errwrite = Handle(errwrite) |
| 1399 |
err_close_fds.append(errwrite) |
| 1400 |
_winapi.CloseHandle(_) |
| 1401 |
ispwrite = True |
| 1402 |
elif stderr == PIPE: |
| 1403 |
errread, errwrite = _winapi.CreatePipe(None, 0) |
| 1404 |
errread, errwrite = Handle(errread), Handle(errwrite) |
| 1405 |
err_close_fds.extend((errread, errwrite)) |
| 1406 |
ispwrite = True |
| 1407 |
elif stderr == STDOUT: |
| 1408 |
errwrite = c2pwrite |
| 1409 |
elif stderr == DEVNULL: |
| 1410 |
errwrite = msvcrt.get_osfhandle(self._get_devnull()) |
| 1411 |
elif isinstance(stderr, int): |
| 1412 |
errwrite = msvcrt.get_osfhandle(stderr) |
| 1413 |
else: |
| 1414 |
|
| 1415 |
errwrite = msvcrt.get_osfhandle(stderr.fileno()) |
| 1416 |
errwrite = self._make_inheritable(errwrite, ispwrite) |
| 1417 |
|
| 1418 |
return (p2cread, p2cwrite, |
| 1419 |
c2pread, c2pwrite, |
| 1420 |
errread, errwrite) |
| 1421 |
|
| 1422 |
|
| 1423 |
def _make_inheritable(self, handle, close=False): |
| 1424 |
"""Return a duplicate of handle, which is inheritable""" |
| 1425 |
h = _winapi.DuplicateHandle( |
| 1426 |
_winapi.GetCurrentProcess(), handle, |
| 1427 |
_winapi.GetCurrentProcess(), 0, 1, |
| 1428 |
_winapi.DUPLICATE_SAME_ACCESS) |
| 1429 |
|
| 1430 |
|
| 1431 |
if close: |
| 1432 |
handle.Close() |
| 1433 |
return Handle(h) |
| 1434 |
|
| 1435 |
|
| 1436 |
def _filter_handle_list(self, handle_list): |
| 1437 |
"""Filter out console handles that can't be used |
| 1438 |
in lpAttributeList["handle_list"] and make sure the list |
| 1439 |
isn't empty. This also removes duplicate handles.""" |
| 1440 |
|
| 1441 |
|
| 1442 |
|
| 1443 |
return list({handle for handle in handle_list |
| 1444 |
if handle & 0x3 != 0x3 |
| 1445 |
or _winapi.GetFileType(handle) != |
| 1446 |
_winapi.FILE_TYPE_CHAR}) |
| 1447 |
|
| 1448 |
|
| 1449 |
def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 1450 |
pass_fds, cwd, env, |
| 1451 |
startupinfo, creationflags, shell, |
| 1452 |
p2cread, p2cwrite, |
| 1453 |
c2pread, c2pwrite, |
| 1454 |
errread, errwrite, |
| 1455 |
unused_restore_signals, |
| 1456 |
unused_gid, unused_gids, unused_uid, |
| 1457 |
unused_umask, |
| 1458 |
unused_start_new_session, unused_process_group): |
| 1459 |
"""Execute program (MS Windows version)""" |
| 1460 |
|
| 1461 |
assert not pass_fds, "pass_fds not supported on Windows." |
| 1462 |
|
| 1463 |
if isinstance(args, str): |
| 1464 |
pass |
| 1465 |
elif isinstance(args, bytes): |
| 1466 |
if shell: |
| 1467 |
raise TypeError('bytes args is not allowed on Windows') |
| 1468 |
args = list2cmdline([args]) |
| 1469 |
elif isinstance(args, os.PathLike): |
| 1470 |
if shell: |
| 1471 |
raise TypeError('path-like args is not allowed when ' |
| 1472 |
'shell is true') |
| 1473 |
args = list2cmdline([args]) |
| 1474 |
else: |
| 1475 |
args = list2cmdline(args) |
| 1476 |
|
| 1477 |
if executable is not None: |
| 1478 |
executable = os.fsdecode(executable) |
| 1479 |
|
| 1480 |
|
| 1481 |
if startupinfo is None: |
| 1482 |
startupinfo = STARTUPINFO() |
| 1483 |
else: |
| 1484 |
|
| 1485 |
|
| 1486 |
startupinfo = startupinfo.copy() |
| 1487 |
|
| 1488 |
use_std_handles = -1 not in (p2cread, c2pwrite, errwrite) |
| 1489 |
if use_std_handles: |
| 1490 |
startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES |
| 1491 |
startupinfo.hStdInput = p2cread |
| 1492 |
startupinfo.hStdOutput = c2pwrite |
| 1493 |
startupinfo.hStdError = errwrite |
| 1494 |
|
| 1495 |
attribute_list = startupinfo.lpAttributeList |
| 1496 |
have_handle_list = bool(attribute_list and |
| 1497 |
"handle_list" in attribute_list and |
| 1498 |
attribute_list["handle_list"]) |
| 1499 |
|
| 1500 |
|
| 1501 |
if have_handle_list or (use_std_handles and close_fds): |
| 1502 |
if attribute_list is None: |
| 1503 |
attribute_list = startupinfo.lpAttributeList = {} |
| 1504 |
handle_list = attribute_list["handle_list"] = \ |
| 1505 |
list(attribute_list.get("handle_list", [])) |
| 1506 |
|
| 1507 |
if use_std_handles: |
| 1508 |
handle_list += [int(p2cread), int(c2pwrite), int(errwrite)] |
| 1509 |
|
| 1510 |
handle_list[:] = self._filter_handle_list(handle_list) |
| 1511 |
|
| 1512 |
if handle_list: |
| 1513 |
if not close_fds: |
| 1514 |
warnings.warn("startupinfo.lpAttributeList['handle_list'] " |
| 1515 |
"overriding close_fds", RuntimeWarning) |
| 1516 |
|
| 1517 |
|
| 1518 |
|
| 1519 |
|
| 1520 |
close_fds = False |
| 1521 |
|
| 1522 |
if shell: |
| 1523 |
startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW |
| 1524 |
startupinfo.wShowWindow = _winapi.SW_HIDE |
| 1525 |
if not executable: |
| 1526 |
|
| 1527 |
|
| 1528 |
|
| 1529 |
|
| 1530 |
|
| 1531 |
comspec = os.environ.get('ComSpec') |
| 1532 |
if not comspec: |
| 1533 |
system_root = os.environ.get('SystemRoot', '') |
| 1534 |
comspec = os.path.join(system_root, 'System32', 'cmd.exe') |
| 1535 |
if not os.path.isabs(comspec): |
| 1536 |
raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set') |
| 1537 |
if os.path.isabs(comspec): |
| 1538 |
executable = comspec |
| 1539 |
else: |
| 1540 |
comspec = executable |
| 1541 |
|
| 1542 |
args = '{} /c "{}"'.format (comspec, args) |
| 1543 |
|
| 1544 |
if cwd is not None: |
| 1545 |
cwd = os.fsdecode(cwd) |
| 1546 |
|
| 1547 |
sys.audit("subprocess.Popen", executable, args, cwd, env) |
| 1548 |
|
| 1549 |
|
| 1550 |
try: |
| 1551 |
hp, ht, pid, tid = _winapi.CreateProcess(executable, args, |
| 1552 |
|
| 1553 |
None, None, |
| 1554 |
int(not close_fds), |
| 1555 |
creationflags, |
| 1556 |
env, |
| 1557 |
cwd, |
| 1558 |
startupinfo) |
| 1559 |
finally: |
| 1560 |
|
| 1561 |
|
| 1562 |
|
| 1563 |
|
| 1564 |
|
| 1565 |
|
| 1566 |
self._close_pipe_fds(p2cread, p2cwrite, |
| 1567 |
c2pread, c2pwrite, |
| 1568 |
errread, errwrite) |
| 1569 |
|
| 1570 |
|
| 1571 |
self._child_created = True |
| 1572 |
self._handle = Handle(hp) |
| 1573 |
self.pid = pid |
| 1574 |
_winapi.CloseHandle(ht) |
| 1575 |
|
| 1576 |
def _internal_poll(self, _deadstate=None, |
| 1577 |
_WaitForSingleObject=_winapi.WaitForSingleObject, |
| 1578 |
_WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0, |
| 1579 |
_GetExitCodeProcess=_winapi.GetExitCodeProcess): |
| 1580 |
"""Check if child process has terminated. Returns returncode |
| 1581 |
attribute. |
| 1582 |
|
| 1583 |
This method is called by __del__, so it can only refer to objects |
| 1584 |
in its local scope. |
| 1585 |
|
| 1586 |
""" |
| 1587 |
if self.returncode is None: |
| 1588 |
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: |
| 1589 |
self.returncode = _GetExitCodeProcess(self._handle) |
| 1590 |
return self.returncode |
| 1591 |
|
| 1592 |
|
| 1593 |
def _wait(self, timeout): |
| 1594 |
"""Internal implementation of wait() on Windows.""" |
| 1595 |
if timeout is None: |
| 1596 |
timeout_millis = _winapi.INFINITE |
| 1597 |
elif timeout <= 0: |
| 1598 |
timeout_millis = 0 |
| 1599 |
else: |
| 1600 |
timeout_millis = int(timeout * 1000) |
| 1601 |
if self.returncode is None: |
| 1602 |
|
| 1603 |
result = _winapi.WaitForSingleObject(self._handle, |
| 1604 |
timeout_millis) |
| 1605 |
if result == _winapi.WAIT_TIMEOUT: |
| 1606 |
raise TimeoutExpired(self.args, timeout) |
| 1607 |
self.returncode = _winapi.GetExitCodeProcess(self._handle) |
| 1608 |
return self.returncode |
| 1609 |
|
| 1610 |
|
| 1611 |
def _readerthread(self, fh, buffer): |
| 1612 |
buffer.append(fh.read()) |
| 1613 |
fh.close() |
| 1614 |
|
| 1615 |
|
| 1616 |
def _communicate(self, input, endtime, orig_timeout): |
| 1617 |
|
| 1618 |
|
| 1619 |
if self.stdout and not hasattr(self, "_stdout_buff"): |
| 1620 |
self._stdout_buff = [] |
| 1621 |
self.stdout_thread = \ |
| 1622 |
threading.Thread(target=self._readerthread, |
| 1623 |
args=(self.stdout, self._stdout_buff)) |
| 1624 |
self.stdout_thread.daemon = True |
| 1625 |
self.stdout_thread.start() |
| 1626 |
if self.stderr and not hasattr(self, "_stderr_buff"): |
| 1627 |
self._stderr_buff = [] |
| 1628 |
self.stderr_thread = \ |
| 1629 |
threading.Thread(target=self._readerthread, |
| 1630 |
args=(self.stderr, self._stderr_buff)) |
| 1631 |
self.stderr_thread.daemon = True |
| 1632 |
self.stderr_thread.start() |
| 1633 |
|
| 1634 |
if self.stdin: |
| 1635 |
self._stdin_write(input) |
| 1636 |
|
| 1637 |
|
| 1638 |
|
| 1639 |
|
| 1640 |
if self.stdout is not None: |
| 1641 |
self.stdout_thread.join(self._remaining_time(endtime)) |
| 1642 |
if self.stdout_thread.is_alive(): |
| 1643 |
raise TimeoutExpired(self.args, orig_timeout) |
| 1644 |
if self.stderr is not None: |
| 1645 |
self.stderr_thread.join(self._remaining_time(endtime)) |
| 1646 |
if self.stderr_thread.is_alive(): |
| 1647 |
raise TimeoutExpired(self.args, orig_timeout) |
| 1648 |
|
| 1649 |
|
| 1650 |
|
| 1651 |
stdout = None |
| 1652 |
stderr = None |
| 1653 |
if self.stdout: |
| 1654 |
stdout = self._stdout_buff |
| 1655 |
self.stdout.close() |
| 1656 |
if self.stderr: |
| 1657 |
stderr = self._stderr_buff |
| 1658 |
self.stderr.close() |
| 1659 |
|
| 1660 |
|
| 1661 |
stdout = stdout[0] if stdout else None |
| 1662 |
stderr = stderr[0] if stderr else None |
| 1663 |
|
| 1664 |
return (stdout, stderr) |
| 1665 |
|
| 1666 |
def send_signal(self, sig): |
| 1667 |
"""Send a signal to the process.""" |
| 1668 |
|
| 1669 |
if self.returncode is not None: |
| 1670 |
return |
| 1671 |
if sig == signal.SIGTERM: |
| 1672 |
self.terminate() |
| 1673 |
elif sig == signal.CTRL_C_EVENT: |
| 1674 |
os.kill(self.pid, signal.CTRL_C_EVENT) |
| 1675 |
elif sig == signal.CTRL_BREAK_EVENT: |
| 1676 |
os.kill(self.pid, signal.CTRL_BREAK_EVENT) |
| 1677 |
else: |
| 1678 |
raise ValueError("Unsupported signal: {}".format(sig)) |
| 1679 |
|
| 1680 |
def terminate(self): |
| 1681 |
"""Terminates the process.""" |
| 1682 |
|
| 1683 |
if self.returncode is not None: |
| 1684 |
return |
| 1685 |
try: |
| 1686 |
_winapi.TerminateProcess(self._handle, 1) |
| 1687 |
except PermissionError: |
| 1688 |
|
| 1689 |
|
| 1690 |
rc = _winapi.GetExitCodeProcess(self._handle) |
| 1691 |
if rc == _winapi.STILL_ACTIVE: |
| 1692 |
raise |
| 1693 |
self.returncode = rc |
| 1694 |
|
| 1695 |
kill = terminate |
| 1696 |
|
| 1697 |
else: |
| 1698 |
|
| 1699 |
|
| 1700 |
|
| 1701 |
def _get_handles(self, stdin, stdout, stderr): |
| 1702 |
"""Construct and return tuple with IO objects: |
| 1703 |
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 1704 |
""" |
| 1705 |
p2cread, p2cwrite = -1, -1 |
| 1706 |
c2pread, c2pwrite = -1, -1 |
| 1707 |
errread, errwrite = -1, -1 |
| 1708 |
|
| 1709 |
with self._on_error_fd_closer() as err_close_fds: |
| 1710 |
if stdin is None: |
| 1711 |
pass |
| 1712 |
elif stdin == PIPE: |
| 1713 |
p2cread, p2cwrite = os.pipe() |
| 1714 |
err_close_fds.extend((p2cread, p2cwrite)) |
| 1715 |
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"): |
| 1716 |
fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize) |
| 1717 |
elif stdin == DEVNULL: |
| 1718 |
p2cread = self._get_devnull() |
| 1719 |
elif isinstance(stdin, int): |
| 1720 |
p2cread = stdin |
| 1721 |
else: |
| 1722 |
|
| 1723 |
p2cread = stdin.fileno() |
| 1724 |
|
| 1725 |
if stdout is None: |
| 1726 |
pass |
| 1727 |
elif stdout == PIPE: |
| 1728 |
c2pread, c2pwrite = os.pipe() |
| 1729 |
err_close_fds.extend((c2pread, c2pwrite)) |
| 1730 |
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"): |
| 1731 |
fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize) |
| 1732 |
elif stdout == DEVNULL: |
| 1733 |
c2pwrite = self._get_devnull() |
| 1734 |
elif isinstance(stdout, int): |
| 1735 |
c2pwrite = stdout |
| 1736 |
else: |
| 1737 |
|
| 1738 |
c2pwrite = stdout.fileno() |
| 1739 |
|
| 1740 |
if stderr is None: |
| 1741 |
pass |
| 1742 |
elif stderr == PIPE: |
| 1743 |
errread, errwrite = os.pipe() |
| 1744 |
err_close_fds.extend((errread, errwrite)) |
| 1745 |
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"): |
| 1746 |
fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize) |
| 1747 |
elif stderr == STDOUT: |
| 1748 |
if c2pwrite != -1: |
| 1749 |
errwrite = c2pwrite |
| 1750 |
else: |
| 1751 |
errwrite = sys.__stdout__.fileno() |
| 1752 |
elif stderr == DEVNULL: |
| 1753 |
errwrite = self._get_devnull() |
| 1754 |
elif isinstance(stderr, int): |
| 1755 |
errwrite = stderr |
| 1756 |
else: |
| 1757 |
|
| 1758 |
errwrite = stderr.fileno() |
| 1759 |
|
| 1760 |
return (p2cread, p2cwrite, |
| 1761 |
c2pread, c2pwrite, |
| 1762 |
errread, errwrite) |
| 1763 |
|
| 1764 |
|
| 1765 |
def _posix_spawn(self, args, executable, env, restore_signals, |
| 1766 |
p2cread, p2cwrite, |
| 1767 |
c2pread, c2pwrite, |
| 1768 |
errread, errwrite): |
| 1769 |
"""Execute program using os.posix_spawn().""" |
| 1770 |
if env is None: |
| 1771 |
env = os.environ |
| 1772 |
|
| 1773 |
kwargs = {} |
| 1774 |
if restore_signals: |
| 1775 |
|
| 1776 |
sigset = [] |
| 1777 |
for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'): |
| 1778 |
signum = getattr(signal, signame, None) |
| 1779 |
if signum is not None: |
| 1780 |
sigset.append(signum) |
| 1781 |
kwargs['setsigdef'] = sigset |
| 1782 |
|
| 1783 |
file_actions = [] |
| 1784 |
for fd in (p2cwrite, c2pread, errread): |
| 1785 |
if fd != -1: |
| 1786 |
file_actions.append((os.POSIX_SPAWN_CLOSE, fd)) |
| 1787 |
for fd, fd2 in ( |
| 1788 |
(p2cread, 0), |
| 1789 |
(c2pwrite, 1), |
| 1790 |
(errwrite, 2), |
| 1791 |
): |
| 1792 |
if fd != -1: |
| 1793 |
file_actions.append((os.POSIX_SPAWN_DUP2, fd, fd2)) |
| 1794 |
if file_actions: |
| 1795 |
kwargs['file_actions'] = file_actions |
| 1796 |
|
| 1797 |
self.pid = os.posix_spawn(executable, args, env, **kwargs) |
| 1798 |
self._child_created = True |
| 1799 |
|
| 1800 |
self._close_pipe_fds(p2cread, p2cwrite, |
| 1801 |
c2pread, c2pwrite, |
| 1802 |
errread, errwrite) |
| 1803 |
|
| 1804 |
def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 1805 |
pass_fds, cwd, env, |
| 1806 |
startupinfo, creationflags, shell, |
| 1807 |
p2cread, p2cwrite, |
| 1808 |
c2pread, c2pwrite, |
| 1809 |
errread, errwrite, |
| 1810 |
restore_signals, |
| 1811 |
gid, gids, uid, umask, |
| 1812 |
start_new_session, process_group): |
| 1813 |
"""Execute program (POSIX version)""" |
| 1814 |
|
| 1815 |
if isinstance(args, (str, bytes)): |
| 1816 |
args = [args] |
| 1817 |
elif isinstance(args, os.PathLike): |
| 1818 |
if shell: |
| 1819 |
raise TypeError('path-like args is not allowed when ' |
| 1820 |
'shell is true') |
| 1821 |
args = [args] |
| 1822 |
else: |
| 1823 |
args = list(args) |
| 1824 |
|
| 1825 |
if shell: |
| 1826 |
|
| 1827 |
unix_shell = ('/system/bin/sh' if |
| 1828 |
hasattr(sys, 'getandroidapilevel') else '/bin/sh') |
| 1829 |
args = [unix_shell, "-c"] + args |
| 1830 |
if executable: |
| 1831 |
args[0] = executable |
| 1832 |
|
| 1833 |
if executable is None: |
| 1834 |
executable = args[0] |
| 1835 |
|
| 1836 |
sys.audit("subprocess.Popen", executable, args, cwd, env) |
| 1837 |
|
| 1838 |
if (_USE_POSIX_SPAWN |
| 1839 |
and os.path.dirname(executable) |
| 1840 |
and preexec_fn is None |
| 1841 |
and not close_fds |
| 1842 |
and not pass_fds |
| 1843 |
and cwd is None |
| 1844 |
and (p2cread == -1 or p2cread > 2) |
| 1845 |
and (c2pwrite == -1 or c2pwrite > 2) |
| 1846 |
and (errwrite == -1 or errwrite > 2) |
| 1847 |
and not start_new_session |
| 1848 |
and process_group == -1 |
| 1849 |
and gid is None |
| 1850 |
and gids is None |
| 1851 |
and uid is None |
| 1852 |
and umask < 0): |
| 1853 |
self._posix_spawn(args, executable, env, restore_signals, |
| 1854 |
p2cread, p2cwrite, |
| 1855 |
c2pread, c2pwrite, |
| 1856 |
errread, errwrite) |
| 1857 |
return |
| 1858 |
|
| 1859 |
orig_executable = executable |
| 1860 |
|
| 1861 |
|
| 1862 |
|
| 1863 |
|
| 1864 |
errpipe_read, errpipe_write = os.pipe() |
| 1865 |
|
| 1866 |
low_fds_to_close = [] |
| 1867 |
while errpipe_write < 3: |
| 1868 |
low_fds_to_close.append(errpipe_write) |
| 1869 |
errpipe_write = os.dup(errpipe_write) |
| 1870 |
for low_fd in low_fds_to_close: |
| 1871 |
os.close(low_fd) |
| 1872 |
try: |
| 1873 |
try: |
| 1874 |
|
| 1875 |
|
| 1876 |
|
| 1877 |
|
| 1878 |
|
| 1879 |
if env is not None: |
| 1880 |
env_list = [] |
| 1881 |
for k, v in env.items(): |
| 1882 |
k = os.fsencode(k) |
| 1883 |
if b'=' in k: |
| 1884 |
raise ValueError("illegal environment variable name") |
| 1885 |
env_list.append(k + b'=' + os.fsencode(v)) |
| 1886 |
else: |
| 1887 |
env_list = None |
| 1888 |
executable = os.fsencode(executable) |
| 1889 |
if os.path.dirname(executable): |
| 1890 |
executable_list = (executable,) |
| 1891 |
else: |
| 1892 |
|
| 1893 |
executable_list = tuple( |
| 1894 |
os.path.join(os.fsencode(dir), executable) |
| 1895 |
for dir in os.get_exec_path(env)) |
| 1896 |
fds_to_keep = set(pass_fds) |
| 1897 |
fds_to_keep.add(errpipe_write) |
| 1898 |
self.pid = _fork_exec( |
| 1899 |
args, executable_list, |
| 1900 |
close_fds, tuple(sorted(map(int, fds_to_keep))), |
| 1901 |
cwd, env_list, |
| 1902 |
p2cread, p2cwrite, c2pread, c2pwrite, |
| 1903 |
errread, errwrite, |
| 1904 |
errpipe_read, errpipe_write, |
| 1905 |
restore_signals, start_new_session, |
| 1906 |
process_group, gid, gids, uid, umask, |
| 1907 |
preexec_fn, _USE_VFORK) |
| 1908 |
self._child_created = True |
| 1909 |
finally: |
| 1910 |
|
| 1911 |
os.close(errpipe_write) |
| 1912 |
|
| 1913 |
self._close_pipe_fds(p2cread, p2cwrite, |
| 1914 |
c2pread, c2pwrite, |
| 1915 |
errread, errwrite) |
| 1916 |
|
| 1917 |
|
| 1918 |
|
| 1919 |
errpipe_data = bytearray() |
| 1920 |
while True: |
| 1921 |
part = os.read(errpipe_read, 50000) |
| 1922 |
errpipe_data += part |
| 1923 |
if not part or len(errpipe_data) > 50000: |
| 1924 |
break |
| 1925 |
finally: |
| 1926 |
|
| 1927 |
os.close(errpipe_read) |
| 1928 |
|
| 1929 |
if errpipe_data: |
| 1930 |
try: |
| 1931 |
pid, sts = os.waitpid(self.pid, 0) |
| 1932 |
if pid == self.pid: |
| 1933 |
self._handle_exitstatus(sts) |
| 1934 |
else: |
| 1935 |
self.returncode = sys.maxsize |
| 1936 |
except ChildProcessError: |
| 1937 |
pass |
| 1938 |
|
| 1939 |
try: |
| 1940 |
exception_name, hex_errno, err_msg = ( |
| 1941 |
errpipe_data.split(b':', 2)) |
| 1942 |
|
| 1943 |
|
| 1944 |
|
| 1945 |
err_msg = err_msg.decode() |
| 1946 |
except ValueError: |
| 1947 |
exception_name = b'SubprocessError' |
| 1948 |
hex_errno = b'0' |
| 1949 |
err_msg = 'Bad exception data from child: {!r}'.format( |
| 1950 |
bytes(errpipe_data)) |
| 1951 |
child_exception_type = getattr( |
| 1952 |
builtins, exception_name.decode('ascii'), |
| 1953 |
SubprocessError) |
| 1954 |
if issubclass(child_exception_type, OSError) and hex_errno: |
| 1955 |
errno_num = int(hex_errno, 16) |
| 1956 |
if err_msg == "noexec:chdir": |
| 1957 |
err_msg = "" |
| 1958 |
|
| 1959 |
err_filename = cwd |
| 1960 |
elif err_msg == "noexec": |
| 1961 |
err_msg = "" |
| 1962 |
err_filename = None |
| 1963 |
else: |
| 1964 |
err_filename = orig_executable |
| 1965 |
if errno_num != 0: |
| 1966 |
err_msg = os.strerror(errno_num) |
| 1967 |
if err_filename is not None: |
| 1968 |
raise child_exception_type(errno_num, err_msg, err_filename) |
| 1969 |
else: |
| 1970 |
raise child_exception_type(errno_num, err_msg) |
| 1971 |
raise child_exception_type(err_msg) |
| 1972 |
|
| 1973 |
|
| 1974 |
def _handle_exitstatus(self, sts, |
| 1975 |
_waitstatus_to_exitcode=_waitstatus_to_exitcode, |
| 1976 |
_WIFSTOPPED=_WIFSTOPPED, |
| 1977 |
_WSTOPSIG=_WSTOPSIG): |
| 1978 |
"""All callers to this function MUST hold self._waitpid_lock.""" |
| 1979 |
|
| 1980 |
|
| 1981 |
if _WIFSTOPPED(sts): |
| 1982 |
self.returncode = -_WSTOPSIG(sts) |
| 1983 |
else: |
| 1984 |
self.returncode = _waitstatus_to_exitcode(sts) |
| 1985 |
|
| 1986 |
def _internal_poll(self, _deadstate=None, _waitpid=_waitpid, |
| 1987 |
_WNOHANG=_WNOHANG, _ECHILD=errno.ECHILD): |
| 1988 |
"""Check if child process has terminated. Returns returncode |
| 1989 |
attribute. |
| 1990 |
|
| 1991 |
This method is called by __del__, so it cannot reference anything |
| 1992 |
outside of the local scope (nor can any methods it calls). |
| 1993 |
|
| 1994 |
""" |
| 1995 |
if self.returncode is None: |
| 1996 |
if not self._waitpid_lock.acquire(False): |
| 1997 |
|
| 1998 |
|
| 1999 |
return None |
| 2000 |
try: |
| 2001 |
if self.returncode is not None: |
| 2002 |
return self.returncode |
| 2003 |
pid, sts = _waitpid(self.pid, _WNOHANG) |
| 2004 |
if pid == self.pid: |
| 2005 |
self._handle_exitstatus(sts) |
| 2006 |
except OSError as e: |
| 2007 |
if _deadstate is not None: |
| 2008 |
self.returncode = _deadstate |
| 2009 |
elif e.errno == _ECHILD: |
| 2010 |
|
| 2011 |
|
| 2012 |
|
| 2013 |
|
| 2014 |
|
| 2015 |
self.returncode = 0 |
| 2016 |
finally: |
| 2017 |
self._waitpid_lock.release() |
| 2018 |
return self.returncode |
| 2019 |
|
| 2020 |
|
| 2021 |
def _try_wait(self, wait_flags): |
| 2022 |
"""All callers to this function MUST hold self._waitpid_lock.""" |
| 2023 |
try: |
| 2024 |
(pid, sts) = os.waitpid(self.pid, wait_flags) |
| 2025 |
except ChildProcessError: |
| 2026 |
|
| 2027 |
|
| 2028 |
|
| 2029 |
pid = self.pid |
| 2030 |
sts = 0 |
| 2031 |
return (pid, sts) |
| 2032 |
|
| 2033 |
|
| 2034 |
def _wait(self, timeout): |
| 2035 |
"""Internal implementation of wait() on POSIX.""" |
| 2036 |
if self.returncode is not None: |
| 2037 |
return self.returncode |
| 2038 |
|
| 2039 |
if timeout is not None: |
| 2040 |
endtime = _time() + timeout |
| 2041 |
|
| 2042 |
|
| 2043 |
delay = 0.0005 |
| 2044 |
while True: |
| 2045 |
if self._waitpid_lock.acquire(False): |
| 2046 |
try: |
| 2047 |
if self.returncode is not None: |
| 2048 |
break |
| 2049 |
(pid, sts) = self._try_wait(os.WNOHANG) |
| 2050 |
assert pid == self.pid or pid == 0 |
| 2051 |
if pid == self.pid: |
| 2052 |
self._handle_exitstatus(sts) |
| 2053 |
break |
| 2054 |
finally: |
| 2055 |
self._waitpid_lock.release() |
| 2056 |
remaining = self._remaining_time(endtime) |
| 2057 |
if remaining <= 0: |
| 2058 |
raise TimeoutExpired(self.args, timeout) |
| 2059 |
delay = min(delay * 2, remaining, .05) |
| 2060 |
time.sleep(delay) |
| 2061 |
else: |
| 2062 |
while self.returncode is None: |
| 2063 |
with self._waitpid_lock: |
| 2064 |
if self.returncode is not None: |
| 2065 |
break |
| 2066 |
(pid, sts) = self._try_wait(0) |
| 2067 |
|
| 2068 |
|
| 2069 |
|
| 2070 |
if pid == self.pid: |
| 2071 |
self._handle_exitstatus(sts) |
| 2072 |
return self.returncode |
| 2073 |
|
| 2074 |
|
| 2075 |
def _communicate(self, input, endtime, orig_timeout): |
| 2076 |
if self.stdin and not self._communication_started: |
| 2077 |
|
| 2078 |
|
| 2079 |
try: |
| 2080 |
self.stdin.flush() |
| 2081 |
except BrokenPipeError: |
| 2082 |
pass |
| 2083 |
if not input: |
| 2084 |
try: |
| 2085 |
self.stdin.close() |
| 2086 |
except BrokenPipeError: |
| 2087 |
pass |
| 2088 |
|
| 2089 |
stdout = None |
| 2090 |
stderr = None |
| 2091 |
|
| 2092 |
|
| 2093 |
if not self._communication_started: |
| 2094 |
self._fileobj2output = {} |
| 2095 |
if self.stdout: |
| 2096 |
self._fileobj2output[self.stdout] = [] |
| 2097 |
if self.stderr: |
| 2098 |
self._fileobj2output[self.stderr] = [] |
| 2099 |
|
| 2100 |
if self.stdout: |
| 2101 |
stdout = self._fileobj2output[self.stdout] |
| 2102 |
if self.stderr: |
| 2103 |
stderr = self._fileobj2output[self.stderr] |
| 2104 |
|
| 2105 |
self._save_input(input) |
| 2106 |
|
| 2107 |
if self._input: |
| 2108 |
input_view = memoryview(self._input) |
| 2109 |
|
| 2110 |
with _PopenSelector() as selector: |
| 2111 |
if self.stdin and input: |
| 2112 |
selector.register(self.stdin, selectors.EVENT_WRITE) |
| 2113 |
if self.stdout and not self.stdout.closed: |
| 2114 |
selector.register(self.stdout, selectors.EVENT_READ) |
| 2115 |
if self.stderr and not self.stderr.closed: |
| 2116 |
selector.register(self.stderr, selectors.EVENT_READ) |
| 2117 |
|
| 2118 |
while selector.get_map(): |
| 2119 |
timeout = self._remaining_time(endtime) |
| 2120 |
if timeout is not None and timeout < 0: |
| 2121 |
self._check_timeout(endtime, orig_timeout, |
| 2122 |
stdout, stderr, |
| 2123 |
skip_check_and_raise=True) |
| 2124 |
raise RuntimeError( |
| 2125 |
'_check_timeout(..., skip_check_and_raise=True) ' |
| 2126 |
'failed to raise TimeoutExpired.') |
| 2127 |
|
| 2128 |
ready = selector.select(timeout) |
| 2129 |
self._check_timeout(endtime, orig_timeout, stdout, stderr) |
| 2130 |
|
| 2131 |
|
| 2132 |
|
| 2133 |
|
| 2134 |
for key, events in ready: |
| 2135 |
if key.fileobj is self.stdin: |
| 2136 |
chunk = input_view[self._input_offset : |
| 2137 |
self._input_offset + _PIPE_BUF] |
| 2138 |
try: |
| 2139 |
self._input_offset += os.write(key.fd, chunk) |
| 2140 |
except BrokenPipeError: |
| 2141 |
selector.unregister(key.fileobj) |
| 2142 |
key.fileobj.close() |
| 2143 |
else: |
| 2144 |
if self._input_offset >= len(self._input): |
| 2145 |
selector.unregister(key.fileobj) |
| 2146 |
key.fileobj.close() |
| 2147 |
elif key.fileobj in (self.stdout, self.stderr): |
| 2148 |
data = os.read(key.fd, 32768) |
| 2149 |
if not data: |
| 2150 |
selector.unregister(key.fileobj) |
| 2151 |
key.fileobj.close() |
| 2152 |
self._fileobj2output[key.fileobj].append(data) |
| 2153 |
|
| 2154 |
self.wait(timeout=self._remaining_time(endtime)) |
| 2155 |
|
| 2156 |
|
| 2157 |
if stdout is not None: |
| 2158 |
stdout = b''.join(stdout) |
| 2159 |
if stderr is not None: |
| 2160 |
stderr = b''.join(stderr) |
| 2161 |
|
| 2162 |
|
| 2163 |
|
| 2164 |
if self.text_mode: |
| 2165 |
if stdout is not None: |
| 2166 |
stdout = self._translate_newlines(stdout, |
| 2167 |
self.stdout.encoding, |
| 2168 |
self.stdout.errors) |
| 2169 |
if stderr is not None: |
| 2170 |
stderr = self._translate_newlines(stderr, |
| 2171 |
self.stderr.encoding, |
| 2172 |
self.stderr.errors) |
| 2173 |
|
| 2174 |
return (stdout, stderr) |
| 2175 |
|
| 2176 |
|
| 2177 |
def _save_input(self, input): |
| 2178 |
|
| 2179 |
|
| 2180 |
|
| 2181 |
if self.stdin and self._input is None: |
| 2182 |
self._input_offset = 0 |
| 2183 |
self._input = input |
| 2184 |
if input is not None and self.text_mode: |
| 2185 |
self._input = self._input.encode(self.stdin.encoding, |
| 2186 |
self.stdin.errors) |
| 2187 |
|
| 2188 |
|
| 2189 |
def send_signal(self, sig): |
| 2190 |
"""Send a signal to the process.""" |
| 2191 |
|
| 2192 |
|
| 2193 |
|
| 2194 |
|
| 2195 |
|
| 2196 |
|
| 2197 |
|
| 2198 |
|
| 2199 |
|
| 2200 |
|
| 2201 |
|
| 2202 |
|
| 2203 |
|
| 2204 |
|
| 2205 |
|
| 2206 |
|
| 2207 |
self.poll() |
| 2208 |
if self.returncode is not None: |
| 2209 |
|
| 2210 |
return |
| 2211 |
|
| 2212 |
|
| 2213 |
|
| 2214 |
|
| 2215 |
try: |
| 2216 |
os.kill(self.pid, sig) |
| 2217 |
except ProcessLookupError: |
| 2218 |
|
| 2219 |
pass |
| 2220 |
|
| 2221 |
def terminate(self): |
| 2222 |
"""Terminate the process with SIGTERM |
| 2223 |
""" |
| 2224 |
self.send_signal(signal.SIGTERM) |
| 2225 |
|
| 2226 |
def kill(self): |
| 2227 |
"""Kill the process with SIGKILL |
| 2228 |
""" |
| 2229 |
self.send_signal(signal.SIGKILL) |