subprocess.py 87 KB

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