subprocess.py 82 KB

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