subprocess.py 76 KB

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