logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

subprocess.py (83734B)


  1. # subprocess - Subprocesses with accessible I/O streams
  2. #
  3. # For more information about this module, see PEP 324.
  4. #
  5. # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
  6. #
  7. # Licensed to PSF under a Contributor Agreement.
  8. r"""Subprocesses with accessible I/O streams
  9. This module allows you to spawn processes, connect to their
  10. input/output/error pipes, and obtain their return codes.
  11. For a complete description of this module see the Python documentation.
  12. Main API
  13. ========
  14. run(...): Runs a command, waits for it to complete, then returns a
  15. CompletedProcess instance.
  16. Popen(...): A class for flexibly executing a command in a new process
  17. Constants
  18. ---------
  19. DEVNULL: Special value that indicates that os.devnull should be used
  20. PIPE: Special value that indicates a pipe should be created
  21. STDOUT: Special value that indicates that stderr should go to stdout
  22. Older API
  23. =========
  24. call(...): Runs a command, waits for it to complete, then returns
  25. the return code.
  26. check_call(...): Same as call() but raises CalledProcessError()
  27. if return code is not 0
  28. check_output(...): Same as check_call() but returns the contents of
  29. stdout instead of a return code
  30. getoutput(...): Runs a command in the shell, waits for it to complete,
  31. then returns the output
  32. getstatusoutput(...): Runs a command in the shell, waits for it to complete,
  33. then returns a (exitcode, output) tuple
  34. """
  35. import builtins
  36. import errno
  37. import io
  38. import os
  39. import time
  40. import signal
  41. import sys
  42. import threading
  43. import warnings
  44. import contextlib
  45. from time import monotonic as _time
  46. import types
  47. try:
  48. import fcntl
  49. except ImportError:
  50. fcntl = None
  51. __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
  52. "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL",
  53. "SubprocessError", "TimeoutExpired", "CompletedProcess"]
  54. # NOTE: We intentionally exclude list2cmdline as it is
  55. # considered an internal implementation detail. issue10838.
  56. try:
  57. import msvcrt
  58. import _winapi
  59. _mswindows = True
  60. except ModuleNotFoundError:
  61. _mswindows = False
  62. import _posixsubprocess
  63. import select
  64. import selectors
  65. else:
  66. from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
  67. STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
  68. STD_ERROR_HANDLE, SW_HIDE,
  69. STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW,
  70. ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS,
  71. HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS,
  72. NORMAL_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS,
  73. CREATE_NO_WINDOW, DETACHED_PROCESS,
  74. CREATE_DEFAULT_ERROR_MODE, CREATE_BREAKAWAY_FROM_JOB)
  75. __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
  76. "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
  77. "STD_ERROR_HANDLE", "SW_HIDE",
  78. "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW",
  79. "STARTUPINFO",
  80. "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
  81. "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
  82. "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
  83. "CREATE_NO_WINDOW", "DETACHED_PROCESS",
  84. "CREATE_DEFAULT_ERROR_MODE", "CREATE_BREAKAWAY_FROM_JOB"])
  85. # Exception classes used by this module.
  86. class SubprocessError(Exception): pass
  87. class CalledProcessError(SubprocessError):
  88. """Raised when run() is called with check=True and the process
  89. returns a non-zero exit status.
  90. Attributes:
  91. cmd, returncode, stdout, stderr, output
  92. """
  93. def __init__(self, returncode, cmd, output=None, stderr=None):
  94. self.returncode = returncode
  95. self.cmd = cmd
  96. self.output = output
  97. self.stderr = stderr
  98. def __str__(self):
  99. if self.returncode and self.returncode < 0:
  100. try:
  101. return "Command '%s' died with %r." % (
  102. self.cmd, signal.Signals(-self.returncode))
  103. except ValueError:
  104. return "Command '%s' died with unknown signal %d." % (
  105. self.cmd, -self.returncode)
  106. else:
  107. return "Command '%s' returned non-zero exit status %d." % (
  108. self.cmd, self.returncode)
  109. @property
  110. def stdout(self):
  111. """Alias for output attribute, to match stderr"""
  112. return self.output
  113. @stdout.setter
  114. def stdout(self, value):
  115. # There's no obvious reason to set this, but allow it anyway so
  116. # .stdout is a transparent alias for .output
  117. self.output = value
  118. class TimeoutExpired(SubprocessError):
  119. """This exception is raised when the timeout expires while waiting for a
  120. child process.
  121. Attributes:
  122. cmd, output, stdout, stderr, timeout
  123. """
  124. def __init__(self, cmd, timeout, output=None, stderr=None):
  125. self.cmd = cmd
  126. self.timeout = timeout
  127. self.output = output
  128. self.stderr = stderr
  129. def __str__(self):
  130. return ("Command '%s' timed out after %s seconds" %
  131. (self.cmd, self.timeout))
  132. @property
  133. def stdout(self):
  134. return self.output
  135. @stdout.setter
  136. def stdout(self, value):
  137. # There's no obvious reason to set this, but allow it anyway so
  138. # .stdout is a transparent alias for .output
  139. self.output = value
  140. if _mswindows:
  141. class STARTUPINFO:
  142. def __init__(self, *, dwFlags=0, hStdInput=None, hStdOutput=None,
  143. hStdError=None, wShowWindow=0, lpAttributeList=None):
  144. self.dwFlags = dwFlags
  145. self.hStdInput = hStdInput
  146. self.hStdOutput = hStdOutput
  147. self.hStdError = hStdError
  148. self.wShowWindow = wShowWindow
  149. self.lpAttributeList = lpAttributeList or {"handle_list": []}
  150. def copy(self):
  151. attr_list = self.lpAttributeList.copy()
  152. if 'handle_list' in attr_list:
  153. attr_list['handle_list'] = list(attr_list['handle_list'])
  154. return STARTUPINFO(dwFlags=self.dwFlags,
  155. hStdInput=self.hStdInput,
  156. hStdOutput=self.hStdOutput,
  157. hStdError=self.hStdError,
  158. wShowWindow=self.wShowWindow,
  159. lpAttributeList=attr_list)
  160. class Handle(int):
  161. closed = False
  162. def Close(self, CloseHandle=_winapi.CloseHandle):
  163. if not self.closed:
  164. self.closed = True
  165. CloseHandle(self)
  166. def Detach(self):
  167. if not self.closed:
  168. self.closed = True
  169. return int(self)
  170. raise ValueError("already closed")
  171. def __repr__(self):
  172. return "%s(%d)" % (self.__class__.__name__, int(self))
  173. __del__ = Close
  174. else:
  175. # When select or poll has indicated that the file is writable,
  176. # we can write up to _PIPE_BUF bytes without risk of blocking.
  177. # POSIX defines PIPE_BUF as >= 512.
  178. _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  179. # poll/select have the advantage of not requiring any extra file
  180. # descriptor, contrarily to epoll/kqueue (also, they require a single
  181. # syscall).
  182. if hasattr(selectors, 'PollSelector'):
  183. _PopenSelector = selectors.PollSelector
  184. else:
  185. _PopenSelector = selectors.SelectSelector
  186. if _mswindows:
  187. # On Windows we just need to close `Popen._handle` when we no longer need
  188. # it, so that the kernel can free it. `Popen._handle` gets closed
  189. # implicitly when the `Popen` instance is finalized (see `Handle.__del__`,
  190. # which is calling `CloseHandle` as requested in [1]), so there is nothing
  191. # for `_cleanup` to do.
  192. #
  193. # [1] https://docs.microsoft.com/en-us/windows/desktop/ProcThread/
  194. # creating-processes
  195. _active = None
  196. def _cleanup():
  197. pass
  198. else:
  199. # This lists holds Popen instances for which the underlying process had not
  200. # exited at the time its __del__ method got called: those processes are
  201. # wait()ed for synchronously from _cleanup() when a new Popen object is
  202. # created, to avoid zombie processes.
  203. _active = []
  204. def _cleanup():
  205. if _active is None:
  206. return
  207. for inst in _active[:]:
  208. res = inst._internal_poll(_deadstate=sys.maxsize)
  209. if res is not None:
  210. try:
  211. _active.remove(inst)
  212. except ValueError:
  213. # This can happen if two threads create a new Popen instance.
  214. # It's harmless that it was already removed, so ignore.
  215. pass
  216. PIPE = -1
  217. STDOUT = -2
  218. DEVNULL = -3
  219. # XXX This function is only used by multiprocessing and the test suite,
  220. # but it's here so that it can be imported when Python is compiled without
  221. # threads.
  222. def _optim_args_from_interpreter_flags():
  223. """Return a list of command-line arguments reproducing the current
  224. optimization settings in sys.flags."""
  225. args = []
  226. value = sys.flags.optimize
  227. if value > 0:
  228. args.append('-' + 'O' * value)
  229. return args
  230. def _args_from_interpreter_flags():
  231. """Return a list of command-line arguments reproducing the current
  232. settings in sys.flags, sys.warnoptions and sys._xoptions."""
  233. flag_opt_map = {
  234. 'debug': 'd',
  235. # 'inspect': 'i',
  236. # 'interactive': 'i',
  237. 'dont_write_bytecode': 'B',
  238. 'no_site': 'S',
  239. 'verbose': 'v',
  240. 'bytes_warning': 'b',
  241. 'quiet': 'q',
  242. # -O is handled in _optim_args_from_interpreter_flags()
  243. }
  244. args = _optim_args_from_interpreter_flags()
  245. for flag, opt in flag_opt_map.items():
  246. v = getattr(sys.flags, flag)
  247. if v > 0:
  248. args.append('-' + opt * v)
  249. if sys.flags.isolated:
  250. args.append('-I')
  251. else:
  252. if sys.flags.ignore_environment:
  253. args.append('-E')
  254. if sys.flags.no_user_site:
  255. args.append('-s')
  256. # -W options
  257. warnopts = sys.warnoptions[:]
  258. bytes_warning = sys.flags.bytes_warning
  259. xoptions = getattr(sys, '_xoptions', {})
  260. dev_mode = ('dev' in xoptions)
  261. if bytes_warning > 1:
  262. warnopts.remove("error::BytesWarning")
  263. elif bytes_warning:
  264. warnopts.remove("default::BytesWarning")
  265. if dev_mode:
  266. warnopts.remove('default')
  267. for opt in warnopts:
  268. args.append('-W' + opt)
  269. # -X options
  270. if dev_mode:
  271. args.extend(('-X', 'dev'))
  272. for opt in ('faulthandler', 'tracemalloc', 'importtime',
  273. 'showrefcount', 'utf8'):
  274. if opt in xoptions:
  275. value = xoptions[opt]
  276. if value is True:
  277. arg = opt
  278. else:
  279. arg = '%s=%s' % (opt, value)
  280. args.extend(('-X', arg))
  281. return args
  282. def call(*popenargs, timeout=None, **kwargs):
  283. """Run command with arguments. Wait for command to complete or
  284. timeout, then return the returncode attribute.
  285. The arguments are the same as for the Popen constructor. Example:
  286. retcode = call(["ls", "-l"])
  287. """
  288. with Popen(*popenargs, **kwargs) as p:
  289. try:
  290. return p.wait(timeout=timeout)
  291. except: # Including KeyboardInterrupt, wait handled that.
  292. p.kill()
  293. # We don't call p.wait() again as p.__exit__ does that for us.
  294. raise
  295. def check_call(*popenargs, **kwargs):
  296. """Run command with arguments. Wait for command to complete. If
  297. the exit code was zero then return, otherwise raise
  298. CalledProcessError. The CalledProcessError object will have the
  299. return code in the returncode attribute.
  300. The arguments are the same as for the call function. Example:
  301. check_call(["ls", "-l"])
  302. """
  303. retcode = call(*popenargs, **kwargs)
  304. if retcode:
  305. cmd = kwargs.get("args")
  306. if cmd is None:
  307. cmd = popenargs[0]
  308. raise CalledProcessError(retcode, cmd)
  309. return 0
  310. def check_output(*popenargs, timeout=None, **kwargs):
  311. r"""Run command with arguments and return its output.
  312. If the exit code was non-zero it raises a CalledProcessError. The
  313. CalledProcessError object will have the return code in the returncode
  314. attribute and output in the output attribute.
  315. The arguments are the same as for the Popen constructor. Example:
  316. >>> check_output(["ls", "-l", "/dev/null"])
  317. b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
  318. The stdout argument is not allowed as it is used internally.
  319. To capture standard error in the result, use stderr=STDOUT.
  320. >>> check_output(["/bin/sh", "-c",
  321. ... "ls -l non_existent_file ; exit 0"],
  322. ... stderr=STDOUT)
  323. b'ls: non_existent_file: No such file or directory\n'
  324. There is an additional optional argument, "input", allowing you to
  325. pass a string to the subprocess's stdin. If you use this argument
  326. you may not also use the Popen constructor's "stdin" argument, as
  327. it too will be used internally. Example:
  328. >>> check_output(["sed", "-e", "s/foo/bar/"],
  329. ... input=b"when in the course of fooman events\n")
  330. b'when in the course of barman events\n'
  331. By default, all communication is in bytes, and therefore any "input"
  332. should be bytes, and the return value will be bytes. If in text mode,
  333. any "input" should be a string, and the return value will be a string
  334. decoded according to locale encoding, or by "encoding" if set. Text mode
  335. is triggered by setting any of text, encoding, errors or universal_newlines.
  336. """
  337. if 'stdout' in kwargs:
  338. raise ValueError('stdout argument not allowed, it will be overridden.')
  339. if 'input' in kwargs and kwargs['input'] is None:
  340. # Explicitly passing input=None was previously equivalent to passing an
  341. # empty string. That is maintained here for backwards compatibility.
  342. if kwargs.get('universal_newlines') or kwargs.get('text'):
  343. empty = ''
  344. else:
  345. empty = b''
  346. kwargs['input'] = empty
  347. return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  348. **kwargs).stdout
  349. class CompletedProcess(object):
  350. """A process that has finished running.
  351. This is returned by run().
  352. Attributes:
  353. args: The list or str args passed to run().
  354. returncode: The exit code of the process, negative for signals.
  355. stdout: The standard output (None if not captured).
  356. stderr: The standard error (None if not captured).
  357. """
  358. def __init__(self, args, returncode, stdout=None, stderr=None):
  359. self.args = args
  360. self.returncode = returncode
  361. self.stdout = stdout
  362. self.stderr = stderr
  363. def __repr__(self):
  364. args = ['args={!r}'.format(self.args),
  365. 'returncode={!r}'.format(self.returncode)]
  366. if self.stdout is not None:
  367. args.append('stdout={!r}'.format(self.stdout))
  368. if self.stderr is not None:
  369. args.append('stderr={!r}'.format(self.stderr))
  370. return "{}({})".format(type(self).__name__, ', '.join(args))
  371. __class_getitem__ = classmethod(types.GenericAlias)
  372. def check_returncode(self):
  373. """Raise CalledProcessError if the exit code is non-zero."""
  374. if self.returncode:
  375. raise CalledProcessError(self.returncode, self.args, self.stdout,
  376. self.stderr)
  377. def run(*popenargs,
  378. input=None, capture_output=False, timeout=None, check=False, **kwargs):
  379. """Run command with arguments and return a CompletedProcess instance.
  380. The returned instance will have attributes args, returncode, stdout and
  381. stderr. By default, stdout and stderr are not captured, and those attributes
  382. will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
  383. If check is True and the exit code was non-zero, it raises a
  384. CalledProcessError. The CalledProcessError object will have the return code
  385. in the returncode attribute, and output & stderr attributes if those streams
  386. were captured.
  387. If timeout is given, and the process takes too long, a TimeoutExpired
  388. exception will be raised.
  389. There is an optional argument "input", allowing you to
  390. pass bytes or a string to the subprocess's stdin. If you use this argument
  391. you may not also use the Popen constructor's "stdin" argument, as
  392. it will be used internally.
  393. By default, all communication is in bytes, and therefore any "input" should
  394. be bytes, and the stdout and stderr will be bytes. If in text mode, any
  395. "input" should be a string, and stdout and stderr will be strings decoded
  396. according to locale encoding, or by "encoding" if set. Text mode is
  397. triggered by setting any of text, encoding, errors or universal_newlines.
  398. The other arguments are the same as for the Popen constructor.
  399. """
  400. if input is not None:
  401. if kwargs.get('stdin') is not None:
  402. raise ValueError('stdin and input arguments may not both be used.')
  403. kwargs['stdin'] = PIPE
  404. if capture_output:
  405. if kwargs.get('stdout') is not None or kwargs.get('stderr') is not None:
  406. raise ValueError('stdout and stderr arguments may not be used '
  407. 'with capture_output.')
  408. kwargs['stdout'] = PIPE
  409. kwargs['stderr'] = PIPE
  410. with Popen(*popenargs, **kwargs) as process:
  411. try:
  412. stdout, stderr = process.communicate(input, timeout=timeout)
  413. except TimeoutExpired as exc:
  414. process.kill()
  415. if _mswindows:
  416. # Windows accumulates the output in a single blocking
  417. # read() call run on child threads, with the timeout
  418. # being done in a join() on those threads. communicate()
  419. # _after_ kill() is required to collect that and add it
  420. # to the exception.
  421. exc.stdout, exc.stderr = process.communicate()
  422. else:
  423. # POSIX _communicate already populated the output so
  424. # far into the TimeoutExpired exception.
  425. process.wait()
  426. raise
  427. except: # Including KeyboardInterrupt, communicate handled that.
  428. process.kill()
  429. # We don't call process.wait() as .__exit__ does that for us.
  430. raise
  431. retcode = process.poll()
  432. if check and retcode:
  433. raise CalledProcessError(retcode, process.args,
  434. output=stdout, stderr=stderr)
  435. return CompletedProcess(process.args, retcode, stdout, stderr)
  436. def list2cmdline(seq):
  437. """
  438. Translate a sequence of arguments into a command line
  439. string, using the same rules as the MS C runtime:
  440. 1) Arguments are delimited by white space, which is either a
  441. space or a tab.
  442. 2) A string surrounded by double quotation marks is
  443. interpreted as a single argument, regardless of white space
  444. contained within. A quoted string can be embedded in an
  445. argument.
  446. 3) A double quotation mark preceded by a backslash is
  447. interpreted as a literal double quotation mark.
  448. 4) Backslashes are interpreted literally, unless they
  449. immediately precede a double quotation mark.
  450. 5) If backslashes immediately precede a double quotation mark,
  451. every pair of backslashes is interpreted as a literal
  452. backslash. If the number of backslashes is odd, the last
  453. backslash escapes the next double quotation mark as
  454. described in rule 3.
  455. """
  456. # See
  457. # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  458. # or search http://msdn.microsoft.com for
  459. # "Parsing C++ Command-Line Arguments"
  460. result = []
  461. needquote = False
  462. for arg in map(os.fsdecode, seq):
  463. bs_buf = []
  464. # Add a space to separate this argument from the others
  465. if result:
  466. result.append(' ')
  467. needquote = (" " in arg) or ("\t" in arg) or not arg
  468. if needquote:
  469. result.append('"')
  470. for c in arg:
  471. if c == '\\':
  472. # Don't know if we need to double yet.
  473. bs_buf.append(c)
  474. elif c == '"':
  475. # Double backslashes.
  476. result.append('\\' * len(bs_buf)*2)
  477. bs_buf = []
  478. result.append('\\"')
  479. else:
  480. # Normal char
  481. if bs_buf:
  482. result.extend(bs_buf)
  483. bs_buf = []
  484. result.append(c)
  485. # Add remaining backslashes, if any.
  486. if bs_buf:
  487. result.extend(bs_buf)
  488. if needquote:
  489. result.extend(bs_buf)
  490. result.append('"')
  491. return ''.join(result)
  492. # Various tools for executing commands and looking at their output and status.
  493. #
  494. def getstatusoutput(cmd):
  495. """Return (exitcode, output) of executing cmd in a shell.
  496. Execute the string 'cmd' in a shell with 'check_output' and
  497. return a 2-tuple (status, output). The locale encoding is used
  498. to decode the output and process newlines.
  499. A trailing newline is stripped from the output.
  500. The exit status for the command can be interpreted
  501. according to the rules for the function 'wait'. Example:
  502. >>> import subprocess
  503. >>> subprocess.getstatusoutput('ls /bin/ls')
  504. (0, '/bin/ls')
  505. >>> subprocess.getstatusoutput('cat /bin/junk')
  506. (1, 'cat: /bin/junk: No such file or directory')
  507. >>> subprocess.getstatusoutput('/bin/junk')
  508. (127, 'sh: /bin/junk: not found')
  509. >>> subprocess.getstatusoutput('/bin/kill $$')
  510. (-15, '')
  511. """
  512. try:
  513. data = check_output(cmd, shell=True, text=True, stderr=STDOUT)
  514. exitcode = 0
  515. except CalledProcessError as ex:
  516. data = ex.output
  517. exitcode = ex.returncode
  518. if data[-1:] == '\n':
  519. data = data[:-1]
  520. return exitcode, data
  521. def getoutput(cmd):
  522. """Return output (stdout or stderr) of executing cmd in a shell.
  523. Like getstatusoutput(), except the exit status is ignored and the return
  524. value is a string containing the command's output. Example:
  525. >>> import subprocess
  526. >>> subprocess.getoutput('ls /bin/ls')
  527. '/bin/ls'
  528. """
  529. return getstatusoutput(cmd)[1]
  530. def _use_posix_spawn():
  531. """Check if posix_spawn() can be used for subprocess.
  532. subprocess requires a posix_spawn() implementation that properly reports
  533. errors to the parent process, & sets errno on the following failures:
  534. * Process attribute actions failed.
  535. * File actions failed.
  536. * exec() failed.
  537. Prefer an implementation which can use vfork() in some cases for best
  538. performance.
  539. """
  540. if _mswindows or not hasattr(os, 'posix_spawn'):
  541. # os.posix_spawn() is not available
  542. return False
  543. if sys.platform in ('darwin', 'sunos5'):
  544. # posix_spawn() is a syscall on both macOS and Solaris,
  545. # and properly reports errors
  546. return True
  547. # Check libc name and runtime libc version
  548. try:
  549. ver = os.confstr('CS_GNU_LIBC_VERSION')
  550. # parse 'glibc 2.28' as ('glibc', (2, 28))
  551. parts = ver.split(maxsplit=1)
  552. if len(parts) != 2:
  553. # reject unknown format
  554. raise ValueError
  555. libc = parts[0]
  556. version = tuple(map(int, parts[1].split('.')))
  557. if sys.platform == 'linux' and libc == 'glibc' and version >= (2, 24):
  558. # glibc 2.24 has a new Linux posix_spawn implementation using vfork
  559. # which properly reports errors to the parent process.
  560. return True
  561. # Note: Don't use the implementation in earlier glibc because it doesn't
  562. # use vfork (even if glibc 2.26 added a pipe to properly report errors
  563. # to the parent process).
  564. except (AttributeError, ValueError, OSError):
  565. # os.confstr() or CS_GNU_LIBC_VERSION value not available
  566. pass
  567. # By default, assume that posix_spawn() does not properly report errors.
  568. return False
  569. _USE_POSIX_SPAWN = _use_posix_spawn()
  570. class Popen:
  571. """ Execute a child program in a new process.
  572. For a complete description of the arguments see the Python documentation.
  573. Arguments:
  574. args: A string, or a sequence of program arguments.
  575. bufsize: supplied as the buffering argument to the open() function when
  576. creating the stdin/stdout/stderr pipe file objects
  577. executable: A replacement program to execute.
  578. stdin, stdout and stderr: These specify the executed programs' standard
  579. input, standard output and standard error file handles, respectively.
  580. preexec_fn: (POSIX only) An object to be called in the child process
  581. just before the child is executed.
  582. close_fds: Controls closing or inheriting of file descriptors.
  583. shell: If true, the command will be executed through the shell.
  584. cwd: Sets the current directory before the child is executed.
  585. env: Defines the environment variables for the new process.
  586. text: If true, decode stdin, stdout and stderr using the given encoding
  587. (if set) or the system default otherwise.
  588. universal_newlines: Alias of text, provided for backwards compatibility.
  589. startupinfo and creationflags (Windows only)
  590. restore_signals (POSIX only)
  591. start_new_session (POSIX only)
  592. group (POSIX only)
  593. extra_groups (POSIX only)
  594. user (POSIX only)
  595. umask (POSIX only)
  596. pass_fds (POSIX only)
  597. encoding and errors: Text mode encoding and error handling to use for
  598. file objects stdin, stdout and stderr.
  599. Attributes:
  600. stdin, stdout, stderr, pid, returncode
  601. """
  602. _child_created = False # Set here since __del__ checks it
  603. def __init__(self, args, bufsize=-1, executable=None,
  604. stdin=None, stdout=None, stderr=None,
  605. preexec_fn=None, close_fds=True,
  606. shell=False, cwd=None, env=None, universal_newlines=None,
  607. startupinfo=None, creationflags=0,
  608. restore_signals=True, start_new_session=False,
  609. pass_fds=(), *, user=None, group=None, extra_groups=None,
  610. encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
  611. """Create new Popen instance."""
  612. _cleanup()
  613. # Held while anything is calling waitpid before returncode has been
  614. # updated to prevent clobbering returncode if wait() or poll() are
  615. # called from multiple threads at once. After acquiring the lock,
  616. # code must re-check self.returncode to see if another thread just
  617. # finished a waitpid() call.
  618. self._waitpid_lock = threading.Lock()
  619. self._input = None
  620. self._communication_started = False
  621. if bufsize is None:
  622. bufsize = -1 # Restore default
  623. if not isinstance(bufsize, int):
  624. raise TypeError("bufsize must be an integer")
  625. if pipesize is None:
  626. pipesize = -1 # Restore default
  627. if not isinstance(pipesize, int):
  628. raise TypeError("pipesize must be an integer")
  629. if _mswindows:
  630. if preexec_fn is not None:
  631. raise ValueError("preexec_fn is not supported on Windows "
  632. "platforms")
  633. else:
  634. # POSIX
  635. if pass_fds and not close_fds:
  636. warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
  637. close_fds = True
  638. if startupinfo is not None:
  639. raise ValueError("startupinfo is only supported on Windows "
  640. "platforms")
  641. if creationflags != 0:
  642. raise ValueError("creationflags is only supported on Windows "
  643. "platforms")
  644. self.args = args
  645. self.stdin = None
  646. self.stdout = None
  647. self.stderr = None
  648. self.pid = None
  649. self.returncode = None
  650. self.encoding = encoding
  651. self.errors = errors
  652. self.pipesize = pipesize
  653. # Validate the combinations of text and universal_newlines
  654. if (text is not None and universal_newlines is not None
  655. and bool(universal_newlines) != bool(text)):
  656. raise SubprocessError('Cannot disambiguate when both text '
  657. 'and universal_newlines are supplied but '
  658. 'different. Pass one or the other.')
  659. # Input and output objects. The general principle is like
  660. # this:
  661. #
  662. # Parent Child
  663. # ------ -----
  664. # p2cwrite ---stdin---> p2cread
  665. # c2pread <--stdout--- c2pwrite
  666. # errread <--stderr--- errwrite
  667. #
  668. # On POSIX, the child objects are file descriptors. On
  669. # Windows, these are Windows file handles. The parent objects
  670. # are file descriptors on both platforms. The parent objects
  671. # are -1 when not using PIPEs. The child objects are -1
  672. # when not redirecting.
  673. (p2cread, p2cwrite,
  674. c2pread, c2pwrite,
  675. errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  676. # We wrap OS handles *before* launching the child, otherwise a
  677. # quickly terminating child could make our fds unwrappable
  678. # (see #8458).
  679. if _mswindows:
  680. if p2cwrite != -1:
  681. p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  682. if c2pread != -1:
  683. c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  684. if errread != -1:
  685. errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  686. self.text_mode = encoding or errors or text or universal_newlines
  687. # PEP 597: We suppress the EncodingWarning in subprocess module
  688. # for now (at Python 3.10), because we focus on files for now.
  689. # This will be changed to encoding = io.text_encoding(encoding)
  690. # in the future.
  691. if self.text_mode and encoding is None:
  692. self.encoding = encoding = "locale"
  693. # How long to resume waiting on a child after the first ^C.
  694. # There is no right value for this. The purpose is to be polite
  695. # yet remain good for interactive users trying to exit a tool.
  696. self._sigint_wait_secs = 0.25 # 1/xkcd221.getRandomNumber()
  697. self._closed_child_pipe_fds = False
  698. if self.text_mode:
  699. if bufsize == 1:
  700. line_buffering = True
  701. # Use the default buffer size for the underlying binary streams
  702. # since they don't support line buffering.
  703. bufsize = -1
  704. else:
  705. line_buffering = False
  706. gid = None
  707. if group is not None:
  708. if not hasattr(os, 'setregid'):
  709. raise ValueError("The 'group' parameter is not supported on the "
  710. "current platform")
  711. elif isinstance(group, str):
  712. try:
  713. import grp
  714. except ImportError:
  715. raise ValueError("The group parameter cannot be a string "
  716. "on systems without the grp module")
  717. gid = grp.getgrnam(group).gr_gid
  718. elif isinstance(group, int):
  719. gid = group
  720. else:
  721. raise TypeError("Group must be a string or an integer, not {}"
  722. .format(type(group)))
  723. if gid < 0:
  724. raise ValueError(f"Group ID cannot be negative, got {gid}")
  725. gids = None
  726. if extra_groups is not None:
  727. if not hasattr(os, 'setgroups'):
  728. raise ValueError("The 'extra_groups' parameter is not "
  729. "supported on the current platform")
  730. elif isinstance(extra_groups, str):
  731. raise ValueError("Groups must be a list, not a string")
  732. gids = []
  733. for extra_group in extra_groups:
  734. if isinstance(extra_group, str):
  735. try:
  736. import grp
  737. except ImportError:
  738. raise ValueError("Items in extra_groups cannot be "
  739. "strings on systems without the "
  740. "grp module")
  741. gids.append(grp.getgrnam(extra_group).gr_gid)
  742. elif isinstance(extra_group, int):
  743. gids.append(extra_group)
  744. else:
  745. raise TypeError("Items in extra_groups must be a string "
  746. "or integer, not {}"
  747. .format(type(extra_group)))
  748. # make sure that the gids are all positive here so we can do less
  749. # checking in the C code
  750. for gid_check in gids:
  751. if gid_check < 0:
  752. raise ValueError(f"Group ID cannot be negative, got {gid_check}")
  753. uid = None
  754. if user is not None:
  755. if not hasattr(os, 'setreuid'):
  756. raise ValueError("The 'user' parameter is not supported on "
  757. "the current platform")
  758. elif isinstance(user, str):
  759. try:
  760. import pwd
  761. except ImportError:
  762. raise ValueError("The user parameter cannot be a string "
  763. "on systems without the pwd module")
  764. uid = pwd.getpwnam(user).pw_uid
  765. elif isinstance(user, int):
  766. uid = user
  767. else:
  768. raise TypeError("User must be a string or an integer")
  769. if uid < 0:
  770. raise ValueError(f"User ID cannot be negative, got {uid}")
  771. try:
  772. if p2cwrite != -1:
  773. self.stdin = io.open(p2cwrite, 'wb', bufsize)
  774. if self.text_mode:
  775. self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
  776. line_buffering=line_buffering,
  777. encoding=encoding, errors=errors)
  778. if c2pread != -1:
  779. self.stdout = io.open(c2pread, 'rb', bufsize)
  780. if self.text_mode:
  781. self.stdout = io.TextIOWrapper(self.stdout,
  782. encoding=encoding, errors=errors)
  783. if errread != -1:
  784. self.stderr = io.open(errread, 'rb', bufsize)
  785. if self.text_mode:
  786. self.stderr = io.TextIOWrapper(self.stderr,
  787. encoding=encoding, errors=errors)
  788. self._execute_child(args, executable, preexec_fn, close_fds,
  789. pass_fds, cwd, env,
  790. startupinfo, creationflags, shell,
  791. p2cread, p2cwrite,
  792. c2pread, c2pwrite,
  793. errread, errwrite,
  794. restore_signals,
  795. gid, gids, uid, umask,
  796. start_new_session)
  797. except:
  798. # Cleanup if the child failed starting.
  799. for f in filter(None, (self.stdin, self.stdout, self.stderr)):
  800. try:
  801. f.close()
  802. except OSError:
  803. pass # Ignore EBADF or other errors.
  804. if not self._closed_child_pipe_fds:
  805. to_close = []
  806. if stdin == PIPE:
  807. to_close.append(p2cread)
  808. if stdout == PIPE:
  809. to_close.append(c2pwrite)
  810. if stderr == PIPE:
  811. to_close.append(errwrite)
  812. if hasattr(self, '_devnull'):
  813. to_close.append(self._devnull)
  814. for fd in to_close:
  815. try:
  816. if _mswindows and isinstance(fd, Handle):
  817. fd.Close()
  818. else:
  819. os.close(fd)
  820. except OSError:
  821. pass
  822. raise
  823. def __repr__(self):
  824. obj_repr = (
  825. f"<{self.__class__.__name__}: "
  826. f"returncode: {self.returncode} args: {self.args!r}>"
  827. )
  828. if len(obj_repr) > 80:
  829. obj_repr = obj_repr[:76] + "...>"
  830. return obj_repr
  831. __class_getitem__ = classmethod(types.GenericAlias)
  832. @property
  833. def universal_newlines(self):
  834. # universal_newlines as retained as an alias of text_mode for API
  835. # compatibility. bpo-31756
  836. return self.text_mode
  837. @universal_newlines.setter
  838. def universal_newlines(self, universal_newlines):
  839. self.text_mode = bool(universal_newlines)
  840. def _translate_newlines(self, data, encoding, errors):
  841. data = data.decode(encoding, errors)
  842. return data.replace("\r\n", "\n").replace("\r", "\n")
  843. def __enter__(self):
  844. return self
  845. def __exit__(self, exc_type, value, traceback):
  846. if self.stdout:
  847. self.stdout.close()
  848. if self.stderr:
  849. self.stderr.close()
  850. try: # Flushing a BufferedWriter may raise an error
  851. if self.stdin:
  852. self.stdin.close()
  853. finally:
  854. if exc_type == KeyboardInterrupt:
  855. # https://bugs.python.org/issue25942
  856. # In the case of a KeyboardInterrupt we assume the SIGINT
  857. # was also already sent to our child processes. We can't
  858. # block indefinitely as that is not user friendly.
  859. # If we have not already waited a brief amount of time in
  860. # an interrupted .wait() or .communicate() call, do so here
  861. # for consistency.
  862. if self._sigint_wait_secs > 0:
  863. try:
  864. self._wait(timeout=self._sigint_wait_secs)
  865. except TimeoutExpired:
  866. pass
  867. self._sigint_wait_secs = 0 # Note that this has been done.
  868. return # resume the KeyboardInterrupt
  869. # Wait for the process to terminate, to avoid zombies.
  870. self.wait()
  871. def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
  872. if not self._child_created:
  873. # We didn't get to successfully create a child process.
  874. return
  875. if self.returncode is None:
  876. # Not reading subprocess exit status creates a zombie process which
  877. # is only destroyed at the parent python process exit
  878. _warn("subprocess %s is still running" % self.pid,
  879. ResourceWarning, source=self)
  880. # In case the child hasn't been waited on, check if it's done.
  881. self._internal_poll(_deadstate=_maxsize)
  882. if self.returncode is None and _active is not None:
  883. # Child is still running, keep us alive until we can wait on it.
  884. _active.append(self)
  885. def _get_devnull(self):
  886. if not hasattr(self, '_devnull'):
  887. self._devnull = os.open(os.devnull, os.O_RDWR)
  888. return self._devnull
  889. def _stdin_write(self, input):
  890. if input:
  891. try:
  892. self.stdin.write(input)
  893. except BrokenPipeError:
  894. pass # communicate() must ignore broken pipe errors.
  895. except OSError as exc:
  896. if exc.errno == errno.EINVAL:
  897. # bpo-19612, bpo-30418: On Windows, stdin.write() fails
  898. # with EINVAL if the child process exited or if the child
  899. # process is still running but closed the pipe.
  900. pass
  901. else:
  902. raise
  903. try:
  904. self.stdin.close()
  905. except BrokenPipeError:
  906. pass # communicate() must ignore broken pipe errors.
  907. except OSError as exc:
  908. if exc.errno == errno.EINVAL:
  909. pass
  910. else:
  911. raise
  912. def communicate(self, input=None, timeout=None):
  913. """Interact with process: Send data to stdin and close it.
  914. Read data from stdout and stderr, until end-of-file is
  915. reached. Wait for process to terminate.
  916. The optional "input" argument should be data to be sent to the
  917. child process, or None, if no data should be sent to the child.
  918. communicate() returns a tuple (stdout, stderr).
  919. By default, all communication is in bytes, and therefore any
  920. "input" should be bytes, and the (stdout, stderr) will be bytes.
  921. If in text mode (indicated by self.text_mode), any "input" should
  922. be a string, and (stdout, stderr) will be strings decoded
  923. according to locale encoding, or by "encoding" if set. Text mode
  924. is triggered by setting any of text, encoding, errors or
  925. universal_newlines.
  926. """
  927. if self._communication_started and input:
  928. raise ValueError("Cannot send input after starting communication")
  929. # Optimization: If we are not worried about timeouts, we haven't
  930. # started communicating, and we have one or zero pipes, using select()
  931. # or threads is unnecessary.
  932. if (timeout is None and not self._communication_started and
  933. [self.stdin, self.stdout, self.stderr].count(None) >= 2):
  934. stdout = None
  935. stderr = None
  936. if self.stdin:
  937. self._stdin_write(input)
  938. elif self.stdout:
  939. stdout = self.stdout.read()
  940. self.stdout.close()
  941. elif self.stderr:
  942. stderr = self.stderr.read()
  943. self.stderr.close()
  944. self.wait()
  945. else:
  946. if timeout is not None:
  947. endtime = _time() + timeout
  948. else:
  949. endtime = None
  950. try:
  951. stdout, stderr = self._communicate(input, endtime, timeout)
  952. except KeyboardInterrupt:
  953. # https://bugs.python.org/issue25942
  954. # See the detailed comment in .wait().
  955. if timeout is not None:
  956. sigint_timeout = min(self._sigint_wait_secs,
  957. self._remaining_time(endtime))
  958. else:
  959. sigint_timeout = self._sigint_wait_secs
  960. self._sigint_wait_secs = 0 # nothing else should wait.
  961. try:
  962. self._wait(timeout=sigint_timeout)
  963. except TimeoutExpired:
  964. pass
  965. raise # resume the KeyboardInterrupt
  966. finally:
  967. self._communication_started = True
  968. sts = self.wait(timeout=self._remaining_time(endtime))
  969. return (stdout, stderr)
  970. def poll(self):
  971. """Check if child process has terminated. Set and return returncode
  972. attribute."""
  973. return self._internal_poll()
  974. def _remaining_time(self, endtime):
  975. """Convenience for _communicate when computing timeouts."""
  976. if endtime is None:
  977. return None
  978. else:
  979. return endtime - _time()
  980. def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq,
  981. skip_check_and_raise=False):
  982. """Convenience for checking if a timeout has expired."""
  983. if endtime is None:
  984. return
  985. if skip_check_and_raise or _time() > endtime:
  986. raise TimeoutExpired(
  987. self.args, orig_timeout,
  988. output=b''.join(stdout_seq) if stdout_seq else None,
  989. stderr=b''.join(stderr_seq) if stderr_seq else None)
  990. def wait(self, timeout=None):
  991. """Wait for child process to terminate; returns self.returncode."""
  992. if timeout is not None:
  993. endtime = _time() + timeout
  994. try:
  995. return self._wait(timeout=timeout)
  996. except KeyboardInterrupt:
  997. # https://bugs.python.org/issue25942
  998. # The first keyboard interrupt waits briefly for the child to
  999. # exit under the common assumption that it also received the ^C
  1000. # generated SIGINT and will exit rapidly.
  1001. if timeout is not None:
  1002. sigint_timeout = min(self._sigint_wait_secs,
  1003. self._remaining_time(endtime))
  1004. else:
  1005. sigint_timeout = self._sigint_wait_secs
  1006. self._sigint_wait_secs = 0 # nothing else should wait.
  1007. try:
  1008. self._wait(timeout=sigint_timeout)
  1009. except TimeoutExpired:
  1010. pass
  1011. raise # resume the KeyboardInterrupt
  1012. def _close_pipe_fds(self,
  1013. p2cread, p2cwrite,
  1014. c2pread, c2pwrite,
  1015. errread, errwrite):
  1016. # self._devnull is not always defined.
  1017. devnull_fd = getattr(self, '_devnull', None)
  1018. with contextlib.ExitStack() as stack:
  1019. if _mswindows:
  1020. if p2cread != -1:
  1021. stack.callback(p2cread.Close)
  1022. if c2pwrite != -1:
  1023. stack.callback(c2pwrite.Close)
  1024. if errwrite != -1:
  1025. stack.callback(errwrite.Close)
  1026. else:
  1027. if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
  1028. stack.callback(os.close, p2cread)
  1029. if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
  1030. stack.callback(os.close, c2pwrite)
  1031. if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
  1032. stack.callback(os.close, errwrite)
  1033. if devnull_fd is not None:
  1034. stack.callback(os.close, devnull_fd)
  1035. # Prevent a double close of these handles/fds from __init__ on error.
  1036. self._closed_child_pipe_fds = True
  1037. if _mswindows:
  1038. #
  1039. # Windows methods
  1040. #
  1041. def _get_handles(self, stdin, stdout, stderr):
  1042. """Construct and return tuple with IO objects:
  1043. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  1044. """
  1045. if stdin is None and stdout is None and stderr is None:
  1046. return (-1, -1, -1, -1, -1, -1)
  1047. p2cread, p2cwrite = -1, -1
  1048. c2pread, c2pwrite = -1, -1
  1049. errread, errwrite = -1, -1
  1050. if stdin is None:
  1051. p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
  1052. if p2cread is None:
  1053. p2cread, _ = _winapi.CreatePipe(None, 0)
  1054. p2cread = Handle(p2cread)
  1055. _winapi.CloseHandle(_)
  1056. elif stdin == PIPE:
  1057. p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
  1058. p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
  1059. elif stdin == DEVNULL:
  1060. p2cread = msvcrt.get_osfhandle(self._get_devnull())
  1061. elif isinstance(stdin, int):
  1062. p2cread = msvcrt.get_osfhandle(stdin)
  1063. else:
  1064. # Assuming file-like object
  1065. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  1066. p2cread = self._make_inheritable(p2cread)
  1067. if stdout is None:
  1068. c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
  1069. if c2pwrite is None:
  1070. _, c2pwrite = _winapi.CreatePipe(None, 0)
  1071. c2pwrite = Handle(c2pwrite)
  1072. _winapi.CloseHandle(_)
  1073. elif stdout == PIPE:
  1074. c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
  1075. c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
  1076. elif stdout == DEVNULL:
  1077. c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
  1078. elif isinstance(stdout, int):
  1079. c2pwrite = msvcrt.get_osfhandle(stdout)
  1080. else:
  1081. # Assuming file-like object
  1082. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  1083. c2pwrite = self._make_inheritable(c2pwrite)
  1084. if stderr is None:
  1085. errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
  1086. if errwrite is None:
  1087. _, errwrite = _winapi.CreatePipe(None, 0)
  1088. errwrite = Handle(errwrite)
  1089. _winapi.CloseHandle(_)
  1090. elif stderr == PIPE:
  1091. errread, errwrite = _winapi.CreatePipe(None, 0)
  1092. errread, errwrite = Handle(errread), Handle(errwrite)
  1093. elif stderr == STDOUT:
  1094. errwrite = c2pwrite
  1095. elif stderr == DEVNULL:
  1096. errwrite = msvcrt.get_osfhandle(self._get_devnull())
  1097. elif isinstance(stderr, int):
  1098. errwrite = msvcrt.get_osfhandle(stderr)
  1099. else:
  1100. # Assuming file-like object
  1101. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  1102. errwrite = self._make_inheritable(errwrite)
  1103. return (p2cread, p2cwrite,
  1104. c2pread, c2pwrite,
  1105. errread, errwrite)
  1106. def _make_inheritable(self, handle):
  1107. """Return a duplicate of handle, which is inheritable"""
  1108. h = _winapi.DuplicateHandle(
  1109. _winapi.GetCurrentProcess(), handle,
  1110. _winapi.GetCurrentProcess(), 0, 1,
  1111. _winapi.DUPLICATE_SAME_ACCESS)
  1112. return Handle(h)
  1113. def _filter_handle_list(self, handle_list):
  1114. """Filter out console handles that can't be used
  1115. in lpAttributeList["handle_list"] and make sure the list
  1116. isn't empty. This also removes duplicate handles."""
  1117. # An handle with it's lowest two bits set might be a special console
  1118. # handle that if passed in lpAttributeList["handle_list"], will
  1119. # cause it to fail.
  1120. return list({handle for handle in handle_list
  1121. if handle & 0x3 != 0x3
  1122. or _winapi.GetFileType(handle) !=
  1123. _winapi.FILE_TYPE_CHAR})
  1124. def _execute_child(self, args, executable, preexec_fn, close_fds,
  1125. pass_fds, cwd, env,
  1126. startupinfo, creationflags, shell,
  1127. p2cread, p2cwrite,
  1128. c2pread, c2pwrite,
  1129. errread, errwrite,
  1130. unused_restore_signals,
  1131. unused_gid, unused_gids, unused_uid,
  1132. unused_umask,
  1133. unused_start_new_session):
  1134. """Execute program (MS Windows version)"""
  1135. assert not pass_fds, "pass_fds not supported on Windows."
  1136. if isinstance(args, str):
  1137. pass
  1138. elif isinstance(args, bytes):
  1139. if shell:
  1140. raise TypeError('bytes args is not allowed on Windows')
  1141. args = list2cmdline([args])
  1142. elif isinstance(args, os.PathLike):
  1143. if shell:
  1144. raise TypeError('path-like args is not allowed when '
  1145. 'shell is true')
  1146. args = list2cmdline([args])
  1147. else:
  1148. args = list2cmdline(args)
  1149. if executable is not None:
  1150. executable = os.fsdecode(executable)
  1151. # Process startup details
  1152. if startupinfo is None:
  1153. startupinfo = STARTUPINFO()
  1154. else:
  1155. # bpo-34044: Copy STARTUPINFO since it is modified above,
  1156. # so the caller can reuse it multiple times.
  1157. startupinfo = startupinfo.copy()
  1158. use_std_handles = -1 not in (p2cread, c2pwrite, errwrite)
  1159. if use_std_handles:
  1160. startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
  1161. startupinfo.hStdInput = p2cread
  1162. startupinfo.hStdOutput = c2pwrite
  1163. startupinfo.hStdError = errwrite
  1164. attribute_list = startupinfo.lpAttributeList
  1165. have_handle_list = bool(attribute_list and
  1166. "handle_list" in attribute_list and
  1167. attribute_list["handle_list"])
  1168. # If we were given an handle_list or need to create one
  1169. if have_handle_list or (use_std_handles and close_fds):
  1170. if attribute_list is None:
  1171. attribute_list = startupinfo.lpAttributeList = {}
  1172. handle_list = attribute_list["handle_list"] = \
  1173. list(attribute_list.get("handle_list", []))
  1174. if use_std_handles:
  1175. handle_list += [int(p2cread), int(c2pwrite), int(errwrite)]
  1176. handle_list[:] = self._filter_handle_list(handle_list)
  1177. if handle_list:
  1178. if not close_fds:
  1179. warnings.warn("startupinfo.lpAttributeList['handle_list'] "
  1180. "overriding close_fds", RuntimeWarning)
  1181. # When using the handle_list we always request to inherit
  1182. # handles but the only handles that will be inherited are
  1183. # the ones in the handle_list
  1184. close_fds = False
  1185. if shell:
  1186. startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
  1187. startupinfo.wShowWindow = _winapi.SW_HIDE
  1188. comspec = os.environ.get("COMSPEC", "cmd.exe")
  1189. args = '{} /c "{}"'.format (comspec, args)
  1190. if cwd is not None:
  1191. cwd = os.fsdecode(cwd)
  1192. sys.audit("subprocess.Popen", executable, args, cwd, env)
  1193. # Start the process
  1194. try:
  1195. hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
  1196. # no special security
  1197. None, None,
  1198. int(not close_fds),
  1199. creationflags,
  1200. env,
  1201. cwd,
  1202. startupinfo)
  1203. finally:
  1204. # Child is launched. Close the parent's copy of those pipe
  1205. # handles that only the child should have open. You need
  1206. # to make sure that no handles to the write end of the
  1207. # output pipe are maintained in this process or else the
  1208. # pipe will not close when the child process exits and the
  1209. # ReadFile will hang.
  1210. self._close_pipe_fds(p2cread, p2cwrite,
  1211. c2pread, c2pwrite,
  1212. errread, errwrite)
  1213. # Retain the process handle, but close the thread handle
  1214. self._child_created = True
  1215. self._handle = Handle(hp)
  1216. self.pid = pid
  1217. _winapi.CloseHandle(ht)
  1218. def _internal_poll(self, _deadstate=None,
  1219. _WaitForSingleObject=_winapi.WaitForSingleObject,
  1220. _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
  1221. _GetExitCodeProcess=_winapi.GetExitCodeProcess):
  1222. """Check if child process has terminated. Returns returncode
  1223. attribute.
  1224. This method is called by __del__, so it can only refer to objects
  1225. in its local scope.
  1226. """
  1227. if self.returncode is None:
  1228. if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
  1229. self.returncode = _GetExitCodeProcess(self._handle)
  1230. return self.returncode
  1231. def _wait(self, timeout):
  1232. """Internal implementation of wait() on Windows."""
  1233. if timeout is None:
  1234. timeout_millis = _winapi.INFINITE
  1235. else:
  1236. timeout_millis = int(timeout * 1000)
  1237. if self.returncode is None:
  1238. # API note: Returns immediately if timeout_millis == 0.
  1239. result = _winapi.WaitForSingleObject(self._handle,
  1240. timeout_millis)
  1241. if result == _winapi.WAIT_TIMEOUT:
  1242. raise TimeoutExpired(self.args, timeout)
  1243. self.returncode = _winapi.GetExitCodeProcess(self._handle)
  1244. return self.returncode
  1245. def _readerthread(self, fh, buffer):
  1246. buffer.append(fh.read())
  1247. fh.close()
  1248. def _communicate(self, input, endtime, orig_timeout):
  1249. # Start reader threads feeding into a list hanging off of this
  1250. # object, unless they've already been started.
  1251. if self.stdout and not hasattr(self, "_stdout_buff"):
  1252. self._stdout_buff = []
  1253. self.stdout_thread = \
  1254. threading.Thread(target=self._readerthread,
  1255. args=(self.stdout, self._stdout_buff))
  1256. self.stdout_thread.daemon = True
  1257. self.stdout_thread.start()
  1258. if self.stderr and not hasattr(self, "_stderr_buff"):
  1259. self._stderr_buff = []
  1260. self.stderr_thread = \
  1261. threading.Thread(target=self._readerthread,
  1262. args=(self.stderr, self._stderr_buff))
  1263. self.stderr_thread.daemon = True
  1264. self.stderr_thread.start()
  1265. if self.stdin:
  1266. self._stdin_write(input)
  1267. # Wait for the reader threads, or time out. If we time out, the
  1268. # threads remain reading and the fds left open in case the user
  1269. # calls communicate again.
  1270. if self.stdout is not None:
  1271. self.stdout_thread.join(self._remaining_time(endtime))
  1272. if self.stdout_thread.is_alive():
  1273. raise TimeoutExpired(self.args, orig_timeout)
  1274. if self.stderr is not None:
  1275. self.stderr_thread.join(self._remaining_time(endtime))
  1276. if self.stderr_thread.is_alive():
  1277. raise TimeoutExpired(self.args, orig_timeout)
  1278. # Collect the output from and close both pipes, now that we know
  1279. # both have been read successfully.
  1280. stdout = None
  1281. stderr = None
  1282. if self.stdout:
  1283. stdout = self._stdout_buff
  1284. self.stdout.close()
  1285. if self.stderr:
  1286. stderr = self._stderr_buff
  1287. self.stderr.close()
  1288. # All data exchanged. Translate lists into strings.
  1289. stdout = stdout[0] if stdout else None
  1290. stderr = stderr[0] if stderr else None
  1291. return (stdout, stderr)
  1292. def send_signal(self, sig):
  1293. """Send a signal to the process."""
  1294. # Don't signal a process that we know has already died.
  1295. if self.returncode is not None:
  1296. return
  1297. if sig == signal.SIGTERM:
  1298. self.terminate()
  1299. elif sig == signal.CTRL_C_EVENT:
  1300. os.kill(self.pid, signal.CTRL_C_EVENT)
  1301. elif sig == signal.CTRL_BREAK_EVENT:
  1302. os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  1303. else:
  1304. raise ValueError("Unsupported signal: {}".format(sig))
  1305. def terminate(self):
  1306. """Terminates the process."""
  1307. # Don't terminate a process that we know has already died.
  1308. if self.returncode is not None:
  1309. return
  1310. try:
  1311. _winapi.TerminateProcess(self._handle, 1)
  1312. except PermissionError:
  1313. # ERROR_ACCESS_DENIED (winerror 5) is received when the
  1314. # process already died.
  1315. rc = _winapi.GetExitCodeProcess(self._handle)
  1316. if rc == _winapi.STILL_ACTIVE:
  1317. raise
  1318. self.returncode = rc
  1319. kill = terminate
  1320. else:
  1321. #
  1322. # POSIX methods
  1323. #
  1324. def _get_handles(self, stdin, stdout, stderr):
  1325. """Construct and return tuple with IO objects:
  1326. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  1327. """
  1328. p2cread, p2cwrite = -1, -1
  1329. c2pread, c2pwrite = -1, -1
  1330. errread, errwrite = -1, -1
  1331. if stdin is None:
  1332. pass
  1333. elif stdin == PIPE:
  1334. p2cread, p2cwrite = os.pipe()
  1335. if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
  1336. fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
  1337. elif stdin == DEVNULL:
  1338. p2cread = self._get_devnull()
  1339. elif isinstance(stdin, int):
  1340. p2cread = stdin
  1341. else:
  1342. # Assuming file-like object
  1343. p2cread = stdin.fileno()
  1344. if stdout is None:
  1345. pass
  1346. elif stdout == PIPE:
  1347. c2pread, c2pwrite = os.pipe()
  1348. if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
  1349. fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
  1350. elif stdout == DEVNULL:
  1351. c2pwrite = self._get_devnull()
  1352. elif isinstance(stdout, int):
  1353. c2pwrite = stdout
  1354. else:
  1355. # Assuming file-like object
  1356. c2pwrite = stdout.fileno()
  1357. if stderr is None:
  1358. pass
  1359. elif stderr == PIPE:
  1360. errread, errwrite = os.pipe()
  1361. if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
  1362. fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
  1363. elif stderr == STDOUT:
  1364. if c2pwrite != -1:
  1365. errwrite = c2pwrite
  1366. else: # child's stdout is not set, use parent's stdout
  1367. errwrite = sys.__stdout__.fileno()
  1368. elif stderr == DEVNULL:
  1369. errwrite = self._get_devnull()
  1370. elif isinstance(stderr, int):
  1371. errwrite = stderr
  1372. else:
  1373. # Assuming file-like object
  1374. errwrite = stderr.fileno()
  1375. return (p2cread, p2cwrite,
  1376. c2pread, c2pwrite,
  1377. errread, errwrite)
  1378. def _posix_spawn(self, args, executable, env, restore_signals,
  1379. p2cread, p2cwrite,
  1380. c2pread, c2pwrite,
  1381. errread, errwrite):
  1382. """Execute program using os.posix_spawn()."""
  1383. if env is None:
  1384. env = os.environ
  1385. kwargs = {}
  1386. if restore_signals:
  1387. # See _Py_RestoreSignals() in Python/pylifecycle.c
  1388. sigset = []
  1389. for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
  1390. signum = getattr(signal, signame, None)
  1391. if signum is not None:
  1392. sigset.append(signum)
  1393. kwargs['setsigdef'] = sigset
  1394. file_actions = []
  1395. for fd in (p2cwrite, c2pread, errread):
  1396. if fd != -1:
  1397. file_actions.append((os.POSIX_SPAWN_CLOSE, fd))
  1398. for fd, fd2 in (
  1399. (p2cread, 0),
  1400. (c2pwrite, 1),
  1401. (errwrite, 2),
  1402. ):
  1403. if fd != -1:
  1404. file_actions.append((os.POSIX_SPAWN_DUP2, fd, fd2))
  1405. if file_actions:
  1406. kwargs['file_actions'] = file_actions
  1407. self.pid = os.posix_spawn(executable, args, env, **kwargs)
  1408. self._child_created = True
  1409. self._close_pipe_fds(p2cread, p2cwrite,
  1410. c2pread, c2pwrite,
  1411. errread, errwrite)
  1412. def _execute_child(self, args, executable, preexec_fn, close_fds,
  1413. pass_fds, cwd, env,
  1414. startupinfo, creationflags, shell,
  1415. p2cread, p2cwrite,
  1416. c2pread, c2pwrite,
  1417. errread, errwrite,
  1418. restore_signals,
  1419. gid, gids, uid, umask,
  1420. start_new_session):
  1421. """Execute program (POSIX version)"""
  1422. if isinstance(args, (str, bytes)):
  1423. args = [args]
  1424. elif isinstance(args, os.PathLike):
  1425. if shell:
  1426. raise TypeError('path-like args is not allowed when '
  1427. 'shell is true')
  1428. args = [args]
  1429. else:
  1430. args = list(args)
  1431. if shell:
  1432. # On Android the default shell is at '/system/bin/sh'.
  1433. unix_shell = ('/system/bin/sh' if
  1434. hasattr(sys, 'getandroidapilevel') else '/bin/sh')
  1435. args = [unix_shell, "-c"] + args
  1436. if executable:
  1437. args[0] = executable
  1438. if executable is None:
  1439. executable = args[0]
  1440. sys.audit("subprocess.Popen", executable, args, cwd, env)
  1441. if (_USE_POSIX_SPAWN
  1442. and os.path.dirname(executable)
  1443. and preexec_fn is None
  1444. and not close_fds
  1445. and not pass_fds
  1446. and cwd is None
  1447. and (p2cread == -1 or p2cread > 2)
  1448. and (c2pwrite == -1 or c2pwrite > 2)
  1449. and (errwrite == -1 or errwrite > 2)
  1450. and not start_new_session
  1451. and gid is None
  1452. and gids is None
  1453. and uid is None
  1454. and umask < 0):
  1455. self._posix_spawn(args, executable, env, restore_signals,
  1456. p2cread, p2cwrite,
  1457. c2pread, c2pwrite,
  1458. errread, errwrite)
  1459. return
  1460. orig_executable = executable
  1461. # For transferring possible exec failure from child to parent.
  1462. # Data format: "exception name:hex errno:description"
  1463. # Pickle is not used; it is complex and involves memory allocation.
  1464. errpipe_read, errpipe_write = os.pipe()
  1465. # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
  1466. low_fds_to_close = []
  1467. while errpipe_write < 3:
  1468. low_fds_to_close.append(errpipe_write)
  1469. errpipe_write = os.dup(errpipe_write)
  1470. for low_fd in low_fds_to_close:
  1471. os.close(low_fd)
  1472. try:
  1473. try:
  1474. # We must avoid complex work that could involve
  1475. # malloc or free in the child process to avoid
  1476. # potential deadlocks, thus we do all this here.
  1477. # and pass it to fork_exec()
  1478. if env is not None:
  1479. env_list = []
  1480. for k, v in env.items():
  1481. k = os.fsencode(k)
  1482. if b'=' in k:
  1483. raise ValueError("illegal environment variable name")
  1484. env_list.append(k + b'=' + os.fsencode(v))
  1485. else:
  1486. env_list = None # Use execv instead of execve.
  1487. executable = os.fsencode(executable)
  1488. if os.path.dirname(executable):
  1489. executable_list = (executable,)
  1490. else:
  1491. # This matches the behavior of os._execvpe().
  1492. executable_list = tuple(
  1493. os.path.join(os.fsencode(dir), executable)
  1494. for dir in os.get_exec_path(env))
  1495. fds_to_keep = set(pass_fds)
  1496. fds_to_keep.add(errpipe_write)
  1497. self.pid = _posixsubprocess.fork_exec(
  1498. args, executable_list,
  1499. close_fds, tuple(sorted(map(int, fds_to_keep))),
  1500. cwd, env_list,
  1501. p2cread, p2cwrite, c2pread, c2pwrite,
  1502. errread, errwrite,
  1503. errpipe_read, errpipe_write,
  1504. restore_signals, start_new_session,
  1505. gid, gids, uid, umask,
  1506. preexec_fn)
  1507. self._child_created = True
  1508. finally:
  1509. # be sure the FD is closed no matter what
  1510. os.close(errpipe_write)
  1511. self._close_pipe_fds(p2cread, p2cwrite,
  1512. c2pread, c2pwrite,
  1513. errread, errwrite)
  1514. # Wait for exec to fail or succeed; possibly raising an
  1515. # exception (limited in size)
  1516. errpipe_data = bytearray()
  1517. while True:
  1518. part = os.read(errpipe_read, 50000)
  1519. errpipe_data += part
  1520. if not part or len(errpipe_data) > 50000:
  1521. break
  1522. finally:
  1523. # be sure the FD is closed no matter what
  1524. os.close(errpipe_read)
  1525. if errpipe_data:
  1526. try:
  1527. pid, sts = os.waitpid(self.pid, 0)
  1528. if pid == self.pid:
  1529. self._handle_exitstatus(sts)
  1530. else:
  1531. self.returncode = sys.maxsize
  1532. except ChildProcessError:
  1533. pass
  1534. try:
  1535. exception_name, hex_errno, err_msg = (
  1536. errpipe_data.split(b':', 2))
  1537. # The encoding here should match the encoding
  1538. # written in by the subprocess implementations
  1539. # like _posixsubprocess
  1540. err_msg = err_msg.decode()
  1541. except ValueError:
  1542. exception_name = b'SubprocessError'
  1543. hex_errno = b'0'
  1544. err_msg = 'Bad exception data from child: {!r}'.format(
  1545. bytes(errpipe_data))
  1546. child_exception_type = getattr(
  1547. builtins, exception_name.decode('ascii'),
  1548. SubprocessError)
  1549. if issubclass(child_exception_type, OSError) and hex_errno:
  1550. errno_num = int(hex_errno, 16)
  1551. child_exec_never_called = (err_msg == "noexec")
  1552. if child_exec_never_called:
  1553. err_msg = ""
  1554. # The error must be from chdir(cwd).
  1555. err_filename = cwd
  1556. else:
  1557. err_filename = orig_executable
  1558. if errno_num != 0:
  1559. err_msg = os.strerror(errno_num)
  1560. raise child_exception_type(errno_num, err_msg, err_filename)
  1561. raise child_exception_type(err_msg)
  1562. def _handle_exitstatus(self, sts,
  1563. waitstatus_to_exitcode=os.waitstatus_to_exitcode,
  1564. _WIFSTOPPED=os.WIFSTOPPED,
  1565. _WSTOPSIG=os.WSTOPSIG):
  1566. """All callers to this function MUST hold self._waitpid_lock."""
  1567. # This method is called (indirectly) by __del__, so it cannot
  1568. # refer to anything outside of its local scope.
  1569. if _WIFSTOPPED(sts):
  1570. self.returncode = -_WSTOPSIG(sts)
  1571. else:
  1572. self.returncode = waitstatus_to_exitcode(sts)
  1573. def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
  1574. _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
  1575. """Check if child process has terminated. Returns returncode
  1576. attribute.
  1577. This method is called by __del__, so it cannot reference anything
  1578. outside of the local scope (nor can any methods it calls).
  1579. """
  1580. if self.returncode is None:
  1581. if not self._waitpid_lock.acquire(False):
  1582. # Something else is busy calling waitpid. Don't allow two
  1583. # at once. We know nothing yet.
  1584. return None
  1585. try:
  1586. if self.returncode is not None:
  1587. return self.returncode # Another thread waited.
  1588. pid, sts = _waitpid(self.pid, _WNOHANG)
  1589. if pid == self.pid:
  1590. self._handle_exitstatus(sts)
  1591. except OSError as e:
  1592. if _deadstate is not None:
  1593. self.returncode = _deadstate
  1594. elif e.errno == _ECHILD:
  1595. # This happens if SIGCLD is set to be ignored or
  1596. # waiting for child processes has otherwise been
  1597. # disabled for our process. This child is dead, we
  1598. # can't get the status.
  1599. # http://bugs.python.org/issue15756
  1600. self.returncode = 0
  1601. finally:
  1602. self._waitpid_lock.release()
  1603. return self.returncode
  1604. def _try_wait(self, wait_flags):
  1605. """All callers to this function MUST hold self._waitpid_lock."""
  1606. try:
  1607. (pid, sts) = os.waitpid(self.pid, wait_flags)
  1608. except ChildProcessError:
  1609. # This happens if SIGCLD is set to be ignored or waiting
  1610. # for child processes has otherwise been disabled for our
  1611. # process. This child is dead, we can't get the status.
  1612. pid = self.pid
  1613. sts = 0
  1614. return (pid, sts)
  1615. def _wait(self, timeout):
  1616. """Internal implementation of wait() on POSIX."""
  1617. if self.returncode is not None:
  1618. return self.returncode
  1619. if timeout is not None:
  1620. endtime = _time() + timeout
  1621. # Enter a busy loop if we have a timeout. This busy loop was
  1622. # cribbed from Lib/threading.py in Thread.wait() at r71065.
  1623. delay = 0.0005 # 500 us -> initial delay of 1 ms
  1624. while True:
  1625. if self._waitpid_lock.acquire(False):
  1626. try:
  1627. if self.returncode is not None:
  1628. break # Another thread waited.
  1629. (pid, sts) = self._try_wait(os.WNOHANG)
  1630. assert pid == self.pid or pid == 0
  1631. if pid == self.pid:
  1632. self._handle_exitstatus(sts)
  1633. break
  1634. finally:
  1635. self._waitpid_lock.release()
  1636. remaining = self._remaining_time(endtime)
  1637. if remaining <= 0:
  1638. raise TimeoutExpired(self.args, timeout)
  1639. delay = min(delay * 2, remaining, .05)
  1640. time.sleep(delay)
  1641. else:
  1642. while self.returncode is None:
  1643. with self._waitpid_lock:
  1644. if self.returncode is not None:
  1645. break # Another thread waited.
  1646. (pid, sts) = self._try_wait(0)
  1647. # Check the pid and loop as waitpid has been known to
  1648. # return 0 even without WNOHANG in odd situations.
  1649. # http://bugs.python.org/issue14396.
  1650. if pid == self.pid:
  1651. self._handle_exitstatus(sts)
  1652. return self.returncode
  1653. def _communicate(self, input, endtime, orig_timeout):
  1654. if self.stdin and not self._communication_started:
  1655. # Flush stdio buffer. This might block, if the user has
  1656. # been writing to .stdin in an uncontrolled fashion.
  1657. try:
  1658. self.stdin.flush()
  1659. except BrokenPipeError:
  1660. pass # communicate() must ignore BrokenPipeError.
  1661. if not input:
  1662. try:
  1663. self.stdin.close()
  1664. except BrokenPipeError:
  1665. pass # communicate() must ignore BrokenPipeError.
  1666. stdout = None
  1667. stderr = None
  1668. # Only create this mapping if we haven't already.
  1669. if not self._communication_started:
  1670. self._fileobj2output = {}
  1671. if self.stdout:
  1672. self._fileobj2output[self.stdout] = []
  1673. if self.stderr:
  1674. self._fileobj2output[self.stderr] = []
  1675. if self.stdout:
  1676. stdout = self._fileobj2output[self.stdout]
  1677. if self.stderr:
  1678. stderr = self._fileobj2output[self.stderr]
  1679. self._save_input(input)
  1680. if self._input:
  1681. input_view = memoryview(self._input)
  1682. with _PopenSelector() as selector:
  1683. if self.stdin and input:
  1684. selector.register(self.stdin, selectors.EVENT_WRITE)
  1685. if self.stdout and not self.stdout.closed:
  1686. selector.register(self.stdout, selectors.EVENT_READ)
  1687. if self.stderr and not self.stderr.closed:
  1688. selector.register(self.stderr, selectors.EVENT_READ)
  1689. while selector.get_map():
  1690. timeout = self._remaining_time(endtime)
  1691. if timeout is not None and timeout < 0:
  1692. self._check_timeout(endtime, orig_timeout,
  1693. stdout, stderr,
  1694. skip_check_and_raise=True)
  1695. raise RuntimeError( # Impossible :)
  1696. '_check_timeout(..., skip_check_and_raise=True) '
  1697. 'failed to raise TimeoutExpired.')
  1698. ready = selector.select(timeout)
  1699. self._check_timeout(endtime, orig_timeout, stdout, stderr)
  1700. # XXX Rewrite these to use non-blocking I/O on the file
  1701. # objects; they are no longer using C stdio!
  1702. for key, events in ready:
  1703. if key.fileobj is self.stdin:
  1704. chunk = input_view[self._input_offset :
  1705. self._input_offset + _PIPE_BUF]
  1706. try:
  1707. self._input_offset += os.write(key.fd, chunk)
  1708. except BrokenPipeError:
  1709. selector.unregister(key.fileobj)
  1710. key.fileobj.close()
  1711. else:
  1712. if self._input_offset >= len(self._input):
  1713. selector.unregister(key.fileobj)
  1714. key.fileobj.close()
  1715. elif key.fileobj in (self.stdout, self.stderr):
  1716. data = os.read(key.fd, 32768)
  1717. if not data:
  1718. selector.unregister(key.fileobj)
  1719. key.fileobj.close()
  1720. self._fileobj2output[key.fileobj].append(data)
  1721. self.wait(timeout=self._remaining_time(endtime))
  1722. # All data exchanged. Translate lists into strings.
  1723. if stdout is not None:
  1724. stdout = b''.join(stdout)
  1725. if stderr is not None:
  1726. stderr = b''.join(stderr)
  1727. # Translate newlines, if requested.
  1728. # This also turns bytes into strings.
  1729. if self.text_mode:
  1730. if stdout is not None:
  1731. stdout = self._translate_newlines(stdout,
  1732. self.stdout.encoding,
  1733. self.stdout.errors)
  1734. if stderr is not None:
  1735. stderr = self._translate_newlines(stderr,
  1736. self.stderr.encoding,
  1737. self.stderr.errors)
  1738. return (stdout, stderr)
  1739. def _save_input(self, input):
  1740. # This method is called from the _communicate_with_*() methods
  1741. # so that if we time out while communicating, we can continue
  1742. # sending input if we retry.
  1743. if self.stdin and self._input is None:
  1744. self._input_offset = 0
  1745. self._input = input
  1746. if input is not None and self.text_mode:
  1747. self._input = self._input.encode(self.stdin.encoding,
  1748. self.stdin.errors)
  1749. def send_signal(self, sig):
  1750. """Send a signal to the process."""
  1751. # bpo-38630: Polling reduces the risk of sending a signal to the
  1752. # wrong process if the process completed, the Popen.returncode
  1753. # attribute is still None, and the pid has been reassigned
  1754. # (recycled) to a new different process. This race condition can
  1755. # happens in two cases.
  1756. #
  1757. # Case 1. Thread A calls Popen.poll(), thread B calls
  1758. # Popen.send_signal(). In thread A, waitpid() succeed and returns
  1759. # the exit status. Thread B calls kill() because poll() in thread A
  1760. # did not set returncode yet. Calling poll() in thread B prevents
  1761. # the race condition thanks to Popen._waitpid_lock.
  1762. #
  1763. # Case 2. waitpid(pid, 0) has been called directly, without
  1764. # using Popen methods: returncode is still None is this case.
  1765. # Calling Popen.poll() will set returncode to a default value,
  1766. # since waitpid() fails with ProcessLookupError.
  1767. self.poll()
  1768. if self.returncode is not None:
  1769. # Skip signalling a process that we know has already died.
  1770. return
  1771. # The race condition can still happen if the race condition
  1772. # described above happens between the returncode test
  1773. # and the kill() call.
  1774. try:
  1775. os.kill(self.pid, sig)
  1776. except ProcessLookupError:
  1777. # Supress the race condition error; bpo-40550.
  1778. pass
  1779. def terminate(self):
  1780. """Terminate the process with SIGTERM
  1781. """
  1782. self.send_signal(signal.SIGTERM)
  1783. def kill(self):
  1784. """Kill the process with SIGKILL
  1785. """
  1786. self.send_signal(signal.SIGKILL)