subprocess.py 87 KB

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