subprocess.py 81 KB

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