subprocess.py 70 KB

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