subprocess.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. """
  2. Cooperative ``subprocess`` module.
  3. .. caution:: On POSIX platforms, this module is not usable from native
  4. threads other than the main thread; attempting to do so will raise
  5. a :exc:`TypeError`. This module depends on libev's fork watchers.
  6. On POSIX systems, fork watchers are implemented using signals, and
  7. the thread to which process-directed signals are delivered `is not
  8. defined`_. Because each native thread has its own gevent/libev
  9. loop, this means that a fork watcher registered with one loop
  10. (thread) may never see the signal about a child it spawned if the
  11. signal is sent to a different thread.
  12. .. note:: The interface of this module is intended to match that of
  13. the standard library :mod:`subprocess` module (with many backwards
  14. compatible extensions from Python 3 backported to Python 2). There
  15. are some small differences between the Python 2 and Python 3
  16. versions of that module (the Python 2 ``TimeoutExpired`` exception,
  17. notably, extends ``Timeout`` and there is no ``SubprocessError``) and between the
  18. POSIX and Windows versions. The HTML documentation here can only
  19. describe one version; for definitive documentation, see the
  20. standard library or the source code.
  21. .. _is not defined: http://www.linuxprogrammingblog.com/all-about-linux-signals?page=11
  22. """
  23. from __future__ import absolute_import, print_function
  24. # Can we split this up to make it cleaner? See https://github.com/gevent/gevent/issues/748
  25. # pylint: disable=too-many-lines
  26. # Import magic
  27. # pylint: disable=undefined-all-variable,undefined-variable
  28. # Most of this we inherit from the standard lib
  29. # pylint: disable=bare-except,too-many-locals,too-many-statements,attribute-defined-outside-init
  30. # pylint: disable=too-many-branches,too-many-instance-attributes
  31. # Most of this is cross-platform
  32. # pylint: disable=no-member,expression-not-assigned,unused-argument,unused-variable
  33. import errno
  34. import gc
  35. import os
  36. import signal
  37. import sys
  38. import traceback
  39. from gevent.event import AsyncResult
  40. from gevent.hub import get_hub, linkproxy, sleep, getcurrent
  41. from gevent._compat import integer_types, string_types, xrange
  42. from gevent._compat import PY3
  43. from gevent._compat import reraise
  44. from gevent._util import _NONE
  45. from gevent._util import copy_globals
  46. from gevent.fileobject import FileObject
  47. from gevent.greenlet import Greenlet, joinall
  48. spawn = Greenlet.spawn
  49. import subprocess as __subprocess__
  50. # Standard functions and classes that this module re-implements in a gevent-aware way.
  51. __implements__ = [
  52. 'Popen',
  53. 'call',
  54. 'check_call',
  55. 'check_output',
  56. ]
  57. if PY3 and not sys.platform.startswith('win32'):
  58. __implements__.append("_posixsubprocess")
  59. _posixsubprocess = None
  60. # Some symbols we define that we expect to export;
  61. # useful for static analysis
  62. PIPE = "PIPE should be imported"
  63. # Standard functions and classes that this module re-imports.
  64. __imports__ = [
  65. 'PIPE',
  66. 'STDOUT',
  67. 'CalledProcessError',
  68. # Windows:
  69. 'CREATE_NEW_CONSOLE',
  70. 'CREATE_NEW_PROCESS_GROUP',
  71. 'STD_INPUT_HANDLE',
  72. 'STD_OUTPUT_HANDLE',
  73. 'STD_ERROR_HANDLE',
  74. 'SW_HIDE',
  75. 'STARTF_USESTDHANDLES',
  76. 'STARTF_USESHOWWINDOW',
  77. ]
  78. __extra__ = [
  79. 'MAXFD',
  80. '_eintr_retry_call',
  81. 'STARTUPINFO',
  82. 'pywintypes',
  83. 'list2cmdline',
  84. '_subprocess',
  85. '_winapi',
  86. # Python 2.5 does not have _subprocess, so we don't use it
  87. # XXX We don't run on Py 2.5 anymore; can/could/should we use _subprocess?
  88. # It's only used on mswindows
  89. 'WAIT_OBJECT_0',
  90. 'WaitForSingleObject',
  91. 'GetExitCodeProcess',
  92. 'GetStdHandle',
  93. 'CreatePipe',
  94. 'DuplicateHandle',
  95. 'GetCurrentProcess',
  96. 'DUPLICATE_SAME_ACCESS',
  97. 'GetModuleFileName',
  98. 'GetVersion',
  99. 'CreateProcess',
  100. 'INFINITE',
  101. 'TerminateProcess',
  102. # These were added for 3.5, but we make them available everywhere.
  103. 'run',
  104. 'CompletedProcess',
  105. ]
  106. if sys.version_info[:2] >= (3, 3):
  107. __imports__ += [
  108. 'DEVNULL',
  109. 'getstatusoutput',
  110. 'getoutput',
  111. 'SubprocessError',
  112. 'TimeoutExpired',
  113. ]
  114. else:
  115. __extra__.append("TimeoutExpired")
  116. if sys.version_info[:2] >= (3, 5):
  117. __extra__.remove('run')
  118. __extra__.remove('CompletedProcess')
  119. __implements__.append('run')
  120. __implements__.append('CompletedProcess')
  121. # Removed in Python 3.5; this is the exact code that was removed:
  122. # https://hg.python.org/cpython/rev/f98b0a5e5ef5
  123. __extra__.remove('MAXFD')
  124. try:
  125. MAXFD = os.sysconf("SC_OPEN_MAX")
  126. except:
  127. MAXFD = 256
  128. if sys.version_info[:2] >= (3, 6):
  129. # This was added to __all__ for windows in 3.6
  130. __extra__.remove('STARTUPINFO')
  131. __imports__.append('STARTUPINFO')
  132. actually_imported = copy_globals(__subprocess__, globals(),
  133. only_names=__imports__,
  134. ignore_missing_names=True)
  135. # anything we couldn't import from here we may need to find
  136. # elsewhere
  137. __extra__.extend(set(__imports__).difference(set(actually_imported)))
  138. __imports__ = actually_imported
  139. del actually_imported
  140. # In Python 3 on Windows, a lot of the functions previously
  141. # in _subprocess moved to _winapi
  142. _subprocess = getattr(__subprocess__, '_subprocess', _NONE)
  143. _winapi = getattr(__subprocess__, '_winapi', _NONE)
  144. _attr_resolution_order = [__subprocess__, _subprocess, _winapi]
  145. for name in list(__extra__):
  146. if name in globals():
  147. continue
  148. value = _NONE
  149. for place in _attr_resolution_order:
  150. value = getattr(place, name, _NONE)
  151. if value is not _NONE:
  152. break
  153. if value is _NONE:
  154. __extra__.remove(name)
  155. else:
  156. globals()[name] = value
  157. del _attr_resolution_order
  158. __all__ = __implements__ + __imports__
  159. # Some other things we want to document
  160. for _x in ('run', 'CompletedProcess', 'TimeoutExpired'):
  161. if _x not in __all__:
  162. __all__.append(_x)
  163. mswindows = sys.platform == 'win32'
  164. if mswindows:
  165. import msvcrt # pylint: disable=import-error
  166. if PY3:
  167. class Handle(int):
  168. closed = False
  169. def Close(self):
  170. if not self.closed:
  171. self.closed = True
  172. _winapi.CloseHandle(self)
  173. def Detach(self):
  174. if not self.closed:
  175. self.closed = True
  176. return int(self)
  177. raise ValueError("already closed")
  178. def __repr__(self):
  179. return "Handle(%d)" % int(self)
  180. __del__ = Close
  181. __str__ = __repr__
  182. else:
  183. import fcntl
  184. import pickle
  185. from gevent import monkey
  186. fork = monkey.get_original('os', 'fork')
  187. from gevent.os import fork_and_watch
  188. def call(*popenargs, **kwargs):
  189. """
  190. call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> returncode
  191. Run command with arguments. Wait for command to complete or
  192. timeout, then return the returncode attribute.
  193. The arguments are the same as for the Popen constructor. Example::
  194. retcode = call(["ls", "-l"])
  195. .. versionchanged:: 1.2a1
  196. The ``timeout`` keyword argument is now accepted on all supported
  197. versions of Python (not just Python 3) and if it expires will raise a
  198. :exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`).
  199. """
  200. timeout = kwargs.pop('timeout', None)
  201. with Popen(*popenargs, **kwargs) as p:
  202. try:
  203. return p.wait(timeout=timeout, _raise_exc=True)
  204. except:
  205. p.kill()
  206. p.wait()
  207. raise
  208. def check_call(*popenargs, **kwargs):
  209. """
  210. check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> 0
  211. Run command with arguments. Wait for command to complete. If
  212. the exit code was zero then return, otherwise raise
  213. :exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
  214. return code in the returncode attribute.
  215. The arguments are the same as for the Popen constructor. Example::
  216. retcode = check_call(["ls", "-l"])
  217. """
  218. retcode = call(*popenargs, **kwargs)
  219. if retcode:
  220. cmd = kwargs.get("args")
  221. if cmd is None:
  222. cmd = popenargs[0]
  223. raise CalledProcessError(retcode, cmd)
  224. return 0
  225. def check_output(*popenargs, **kwargs):
  226. r"""
  227. check_output(args, *, input=None, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None) -> output
  228. Run command with arguments and return its output.
  229. If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
  230. ``CalledProcessError`` object will have the return code in the returncode
  231. attribute and output in the output attribute.
  232. The arguments are the same as for the Popen constructor. Example::
  233. >>> check_output(["ls", "-1", "/dev/null"])
  234. '/dev/null\n'
  235. The ``stdout`` argument is not allowed as it is used internally.
  236. To capture standard error in the result, use ``stderr=STDOUT``::
  237. >>> check_output(["/bin/sh", "-c",
  238. ... "ls -l non_existent_file ; exit 0"],
  239. ... stderr=STDOUT)
  240. 'ls: non_existent_file: No such file or directory\n'
  241. There is an additional optional argument, "input", allowing you to
  242. pass a string to the subprocess's stdin. If you use this argument
  243. you may not also use the Popen constructor's "stdin" argument, as
  244. it too will be used internally. Example::
  245. >>> check_output(["sed", "-e", "s/foo/bar/"],
  246. ... input=b"when in the course of fooman events\n")
  247. 'when in the course of barman events\n'
  248. If ``universal_newlines=True`` is passed, the return value will be a
  249. string rather than bytes.
  250. .. versionchanged:: 1.2a1
  251. The ``timeout`` keyword argument is now accepted on all supported
  252. versions of Python (not just Python 3) and if it expires will raise a
  253. :exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`).
  254. .. versionchanged:: 1.2a1
  255. The ``input`` keyword argument is now accepted on all supported
  256. versions of Python, not just Python 3
  257. """
  258. timeout = kwargs.pop('timeout', None)
  259. if 'stdout' in kwargs:
  260. raise ValueError('stdout argument not allowed, it will be overridden.')
  261. if 'input' in kwargs:
  262. if 'stdin' in kwargs:
  263. raise ValueError('stdin and input arguments may not both be used.')
  264. inputdata = kwargs['input']
  265. del kwargs['input']
  266. kwargs['stdin'] = PIPE
  267. else:
  268. inputdata = None
  269. with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
  270. try:
  271. output, unused_err = process.communicate(inputdata, timeout=timeout)
  272. except TimeoutExpired:
  273. process.kill()
  274. output, unused_err = process.communicate()
  275. raise TimeoutExpired(process.args, timeout, output=output)
  276. except:
  277. process.kill()
  278. process.wait()
  279. raise
  280. retcode = process.poll()
  281. if retcode:
  282. raise CalledProcessError(retcode, process.args, output=output)
  283. return output
  284. _PLATFORM_DEFAULT_CLOSE_FDS = object()
  285. if 'TimeoutExpired' not in globals():
  286. # Python 2
  287. # Make TimeoutExpired inherit from _Timeout so it can be caught
  288. # the way we used to throw things (except Timeout), but make sure it doesn't
  289. # init a timer. Note that we can't have a fake 'SubprocessError' that inherits
  290. # from exception, because we need TimeoutExpired to just be a BaseException for
  291. # bwc.
  292. from gevent.timeout import Timeout as _Timeout
  293. class TimeoutExpired(_Timeout):
  294. """
  295. This exception is raised when the timeout expires while waiting for
  296. a child process in `communicate`.
  297. Under Python 2, this is a gevent extension with the same name as the
  298. Python 3 class for source-code forward compatibility. However, it extends
  299. :class:`gevent.timeout.Timeout` for backwards compatibility (because
  300. we used to just raise a plain ``Timeout``); note that ``Timeout`` is a
  301. ``BaseException``, *not* an ``Exception``.
  302. .. versionadded:: 1.2a1
  303. """
  304. def __init__(self, cmd, timeout, output=None):
  305. _Timeout.__init__(self, timeout, _use_timer=False)
  306. self.cmd = cmd
  307. self.timeout = timeout
  308. self.output = output
  309. def __str__(self):
  310. return ("Command '%s' timed out after %s seconds" %
  311. (self.cmd, self.timeout))
  312. class Popen(object):
  313. """
  314. The underlying process creation and management in this module is
  315. handled by the Popen class. It offers a lot of flexibility so that
  316. developers are able to handle the less common cases not covered by
  317. the convenience functions.
  318. .. seealso:: :class:`subprocess.Popen`
  319. This class should have the same interface as the standard library class.
  320. .. versionchanged:: 1.2a1
  321. Instances can now be used as context managers under Python 2.7. Previously
  322. this was restricted to Python 3.
  323. .. versionchanged:: 1.2a1
  324. Instances now save the ``args`` attribute under Python 2.7. Previously this was
  325. restricted to Python 3.
  326. """
  327. def __init__(self, args, bufsize=None, executable=None,
  328. stdin=None, stdout=None, stderr=None,
  329. preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False,
  330. cwd=None, env=None, universal_newlines=False,
  331. startupinfo=None, creationflags=0, threadpool=None,
  332. **kwargs):
  333. """Create new Popen instance.
  334. :param kwargs: *Only* allowed under Python 3; under Python 2, any
  335. unrecognized keyword arguments will result in a :exc:`TypeError`.
  336. Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``,
  337. ``restore_signals``, ``encoding`` and ``errors``
  338. .. versionchanged:: 1.2b1
  339. Add the ``encoding`` and ``errors`` parameters for Python 3.
  340. """
  341. if not PY3 and kwargs:
  342. raise TypeError("Got unexpected keyword arguments", kwargs)
  343. pass_fds = kwargs.pop('pass_fds', ())
  344. start_new_session = kwargs.pop('start_new_session', False)
  345. restore_signals = kwargs.pop('restore_signals', True)
  346. # Added in 3.6. These are kept as ivars
  347. encoding = self.encoding = kwargs.pop('encoding', None)
  348. errors = self.errors = kwargs.pop('errors', None)
  349. hub = get_hub()
  350. if bufsize is None:
  351. # bufsize has different defaults on Py3 and Py2
  352. if PY3:
  353. bufsize = -1
  354. else:
  355. bufsize = 0
  356. if not isinstance(bufsize, integer_types):
  357. raise TypeError("bufsize must be an integer")
  358. if mswindows:
  359. if preexec_fn is not None:
  360. raise ValueError("preexec_fn is not supported on Windows "
  361. "platforms")
  362. any_stdio_set = (stdin is not None or stdout is not None or
  363. stderr is not None)
  364. if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
  365. if any_stdio_set:
  366. close_fds = False
  367. else:
  368. close_fds = True
  369. elif close_fds and any_stdio_set:
  370. raise ValueError("close_fds is not supported on Windows "
  371. "platforms if you redirect stdin/stdout/stderr")
  372. if threadpool is None:
  373. threadpool = hub.threadpool
  374. self.threadpool = threadpool
  375. self._waiting = False
  376. else:
  377. # POSIX
  378. if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
  379. # close_fds has different defaults on Py3/Py2
  380. if PY3: # pylint: disable=simplifiable-if-statement
  381. close_fds = True
  382. else:
  383. close_fds = False
  384. if pass_fds and not close_fds:
  385. import warnings
  386. warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
  387. close_fds = True
  388. if startupinfo is not None:
  389. raise ValueError("startupinfo is only supported on Windows "
  390. "platforms")
  391. if creationflags != 0:
  392. raise ValueError("creationflags is only supported on Windows "
  393. "platforms")
  394. assert threadpool is None
  395. self._loop = hub.loop
  396. self.args = args # Previously this was Py3 only.
  397. self.stdin = None
  398. self.stdout = None
  399. self.stderr = None
  400. self.pid = None
  401. self.returncode = None
  402. self.universal_newlines = universal_newlines
  403. self.result = AsyncResult()
  404. # Input and output objects. The general principle is like
  405. # this:
  406. #
  407. # Parent Child
  408. # ------ -----
  409. # p2cwrite ---stdin---> p2cread
  410. # c2pread <--stdout--- c2pwrite
  411. # errread <--stderr--- errwrite
  412. #
  413. # On POSIX, the child objects are file descriptors. On
  414. # Windows, these are Windows file handles. The parent objects
  415. # are file descriptors on both platforms. The parent objects
  416. # are None when not using PIPEs. The child objects are None
  417. # when not redirecting.
  418. (p2cread, p2cwrite,
  419. c2pread, c2pwrite,
  420. errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  421. # We wrap OS handles *before* launching the child, otherwise a
  422. # quickly terminating child could make our fds unwrappable
  423. # (see #8458).
  424. if mswindows:
  425. if p2cwrite is not None:
  426. p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  427. if c2pread is not None:
  428. c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  429. if errread is not None:
  430. errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  431. text_mode = PY3 and (self.encoding or self.errors or universal_newlines)
  432. if p2cwrite is not None:
  433. if PY3 and text_mode:
  434. # Under Python 3, if we left on the 'b' we'd get different results
  435. # depending on whether we used FileObjectPosix or FileObjectThread
  436. self.stdin = FileObject(p2cwrite, 'wb', bufsize)
  437. self.stdin.translate_newlines(None,
  438. write_through=True,
  439. line_buffering=(bufsize == 1),
  440. encoding=self.encoding, errors=self.errors)
  441. else:
  442. self.stdin = FileObject(p2cwrite, 'wb', bufsize)
  443. if c2pread is not None:
  444. if universal_newlines or text_mode:
  445. if PY3:
  446. # FileObjectThread doesn't support the 'U' qualifier
  447. # with a bufsize of 0
  448. self.stdout = FileObject(c2pread, 'rb', bufsize)
  449. # NOTE: Universal Newlines are broken on Windows/Py3, at least
  450. # in some cases. This is true in the stdlib subprocess module
  451. # as well; the following line would fix the test cases in
  452. # test__subprocess.py that depend on python_universal_newlines,
  453. # but would be inconsistent with the stdlib:
  454. #msvcrt.setmode(self.stdout.fileno(), os.O_TEXT)
  455. self.stdout.translate_newlines('r', encoding=self.encoding, errors=self.errors)
  456. else:
  457. self.stdout = FileObject(c2pread, 'rU', bufsize)
  458. else:
  459. self.stdout = FileObject(c2pread, 'rb', bufsize)
  460. if errread is not None:
  461. if universal_newlines or text_mode:
  462. if PY3:
  463. self.stderr = FileObject(errread, 'rb', bufsize)
  464. self.stderr.translate_newlines(None, encoding=encoding, errors=errors)
  465. else:
  466. self.stderr = FileObject(errread, 'rU', bufsize)
  467. else:
  468. self.stderr = FileObject(errread, 'rb', bufsize)
  469. self._closed_child_pipe_fds = False
  470. try:
  471. self._execute_child(args, executable, preexec_fn, close_fds,
  472. pass_fds, cwd, env, universal_newlines,
  473. startupinfo, creationflags, shell,
  474. p2cread, p2cwrite,
  475. c2pread, c2pwrite,
  476. errread, errwrite,
  477. restore_signals, start_new_session)
  478. except:
  479. # Cleanup if the child failed starting.
  480. # (gevent: New in python3, but reported as gevent bug in #347.
  481. # Note that under Py2, any error raised below will replace the
  482. # original error so we have to use reraise)
  483. if not PY3:
  484. exc_info = sys.exc_info()
  485. for f in filter(None, (self.stdin, self.stdout, self.stderr)):
  486. try:
  487. f.close()
  488. except (OSError, IOError):
  489. pass # Ignore EBADF or other errors.
  490. if not self._closed_child_pipe_fds:
  491. to_close = []
  492. if stdin == PIPE:
  493. to_close.append(p2cread)
  494. if stdout == PIPE:
  495. to_close.append(c2pwrite)
  496. if stderr == PIPE:
  497. to_close.append(errwrite)
  498. if hasattr(self, '_devnull'):
  499. to_close.append(self._devnull)
  500. for fd in to_close:
  501. try:
  502. os.close(fd)
  503. except (OSError, IOError):
  504. pass
  505. if not PY3:
  506. try:
  507. reraise(*exc_info)
  508. finally:
  509. del exc_info
  510. raise
  511. def __repr__(self):
  512. return '<%s at 0x%x pid=%r returncode=%r>' % (self.__class__.__name__, id(self), self.pid, self.returncode)
  513. def _on_child(self, watcher):
  514. watcher.stop()
  515. status = watcher.rstatus
  516. if os.WIFSIGNALED(status):
  517. self.returncode = -os.WTERMSIG(status)
  518. else:
  519. self.returncode = os.WEXITSTATUS(status)
  520. self.result.set(self.returncode)
  521. def _get_devnull(self):
  522. if not hasattr(self, '_devnull'):
  523. self._devnull = os.open(os.devnull, os.O_RDWR)
  524. return self._devnull
  525. _stdout_buffer = None
  526. _stderr_buffer = None
  527. def communicate(self, input=None, timeout=None):
  528. """Interact with process: Send data to stdin. Read data from
  529. stdout and stderr, until end-of-file is reached. Wait for
  530. process to terminate. The optional input argument should be a
  531. string to be sent to the child process, or None, if no data
  532. should be sent to the child.
  533. communicate() returns a tuple (stdout, stderr).
  534. :keyword timeout: Under Python 2, this is a gevent extension; if
  535. given and it expires, we will raise :exc:`TimeoutExpired`, which
  536. extends :exc:`gevent.timeout.Timeout` (note that this only extends :exc:`BaseException`,
  537. *not* :exc:`Exception`)
  538. Under Python 3, this raises the standard :exc:`TimeoutExpired` exception.
  539. .. versionchanged:: 1.1a2
  540. Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout`
  541. exception. Previously, we silently returned.
  542. .. versionchanged:: 1.1b5
  543. Honor a *timeout* even if there's no way to communicate with the child
  544. (stdin, stdout, and stderr are not pipes).
  545. """
  546. greenlets = []
  547. if self.stdin:
  548. greenlets.append(spawn(write_and_close, self.stdin, input))
  549. # If the timeout parameter is used, and the caller calls back after
  550. # getting a TimeoutExpired exception, we can wind up with multiple
  551. # greenlets trying to run and read from and close stdout/stderr.
  552. # That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'.
  553. # We can't just kill the previous greenlets when a timeout happens,
  554. # though, because we risk losing the output collected by that greenlet
  555. # (and Python 3, where timeout is an official parameter, explicitly says
  556. # that no output should be lost in the event of a timeout.) Instead, we're
  557. # watching for the exception and ignoring it. It's not elegant,
  558. # but it works
  559. if self.stdout:
  560. def _read_out():
  561. try:
  562. data = self.stdout.read()
  563. except RuntimeError:
  564. return
  565. if self._stdout_buffer is not None:
  566. self._stdout_buffer += data
  567. else:
  568. self._stdout_buffer = data
  569. stdout = spawn(_read_out)
  570. greenlets.append(stdout)
  571. else:
  572. stdout = None
  573. if self.stderr:
  574. def _read_err():
  575. try:
  576. data = self.stderr.read()
  577. except RuntimeError:
  578. return
  579. if self._stderr_buffer is not None:
  580. self._stderr_buffer += data
  581. else:
  582. self._stderr_buffer = data
  583. stderr = spawn(_read_err)
  584. greenlets.append(stderr)
  585. else:
  586. stderr = None
  587. # If we were given stdin=stdout=stderr=None, we have no way to
  588. # communicate with the child, and thus no greenlets to wait
  589. # on. This is a nonsense case, but it comes up in the test
  590. # case for Python 3.5 (test_subprocess.py
  591. # RunFuncTestCase.test_timeout). Instead, we go directly to
  592. # self.wait
  593. if not greenlets and timeout is not None:
  594. self.wait(timeout=timeout, _raise_exc=True)
  595. done = joinall(greenlets, timeout=timeout)
  596. if timeout is not None and len(done) != len(greenlets):
  597. raise TimeoutExpired(self.args, timeout)
  598. if self.stdout:
  599. try:
  600. self.stdout.close()
  601. except RuntimeError:
  602. pass
  603. if self.stderr:
  604. try:
  605. self.stderr.close()
  606. except RuntimeError:
  607. pass
  608. self.wait()
  609. stdout_value = self._stdout_buffer
  610. self._stdout_buffer = None
  611. stderr_value = self._stderr_buffer
  612. self._stderr_buffer = None
  613. # XXX: Under python 3 in universal newlines mode we should be
  614. # returning str, not bytes
  615. return (None if stdout is None else stdout_value or b'',
  616. None if stderr is None else stderr_value or b'')
  617. def poll(self):
  618. """Check if child process has terminated. Set and return :attr:`returncode` attribute."""
  619. return self._internal_poll()
  620. def __enter__(self):
  621. return self
  622. def __exit__(self, t, v, tb):
  623. if self.stdout:
  624. self.stdout.close()
  625. if self.stderr:
  626. self.stderr.close()
  627. try: # Flushing a BufferedWriter may raise an error
  628. if self.stdin:
  629. self.stdin.close()
  630. finally:
  631. # Wait for the process to terminate, to avoid zombies.
  632. # JAM: gevent: If the process never terminates, this
  633. # blocks forever.
  634. self.wait()
  635. def _gevent_result_wait(self, timeout=None, raise_exc=PY3):
  636. result = self.result.wait(timeout=timeout)
  637. if raise_exc and timeout is not None and not self.result.ready():
  638. raise TimeoutExpired(self.args, timeout)
  639. return result
  640. if mswindows:
  641. #
  642. # Windows methods
  643. #
  644. def _get_handles(self, stdin, stdout, stderr):
  645. """Construct and return tuple with IO objects:
  646. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  647. """
  648. if stdin is None and stdout is None and stderr is None:
  649. return (None, None, None, None, None, None)
  650. p2cread, p2cwrite = None, None
  651. c2pread, c2pwrite = None, None
  652. errread, errwrite = None, None
  653. try:
  654. DEVNULL
  655. except NameError:
  656. _devnull = object()
  657. else:
  658. _devnull = DEVNULL
  659. if stdin is None:
  660. p2cread = GetStdHandle(STD_INPUT_HANDLE)
  661. if p2cread is None:
  662. p2cread, _ = CreatePipe(None, 0)
  663. if PY3:
  664. p2cread = Handle(p2cread)
  665. _winapi.CloseHandle(_)
  666. elif stdin == PIPE:
  667. p2cread, p2cwrite = CreatePipe(None, 0)
  668. if PY3:
  669. p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
  670. elif stdin == _devnull:
  671. p2cread = msvcrt.get_osfhandle(self._get_devnull())
  672. elif isinstance(stdin, int):
  673. p2cread = msvcrt.get_osfhandle(stdin)
  674. else:
  675. # Assuming file-like object
  676. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  677. p2cread = self._make_inheritable(p2cread)
  678. if stdout is None:
  679. c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
  680. if c2pwrite is None:
  681. _, c2pwrite = CreatePipe(None, 0)
  682. if PY3:
  683. c2pwrite = Handle(c2pwrite)
  684. _winapi.CloseHandle(_)
  685. elif stdout == PIPE:
  686. c2pread, c2pwrite = CreatePipe(None, 0)
  687. if PY3:
  688. c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
  689. elif stdout == _devnull:
  690. c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
  691. elif isinstance(stdout, int):
  692. c2pwrite = msvcrt.get_osfhandle(stdout)
  693. else:
  694. # Assuming file-like object
  695. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  696. c2pwrite = self._make_inheritable(c2pwrite)
  697. if stderr is None:
  698. errwrite = GetStdHandle(STD_ERROR_HANDLE)
  699. if errwrite is None:
  700. _, errwrite = CreatePipe(None, 0)
  701. if PY3:
  702. errwrite = Handle(errwrite)
  703. _winapi.CloseHandle(_)
  704. elif stderr == PIPE:
  705. errread, errwrite = CreatePipe(None, 0)
  706. if PY3:
  707. errread, errwrite = Handle(errread), Handle(errwrite)
  708. elif stderr == STDOUT:
  709. errwrite = c2pwrite
  710. elif stderr == _devnull:
  711. errwrite = msvcrt.get_osfhandle(self._get_devnull())
  712. elif isinstance(stderr, int):
  713. errwrite = msvcrt.get_osfhandle(stderr)
  714. else:
  715. # Assuming file-like object
  716. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  717. errwrite = self._make_inheritable(errwrite)
  718. return (p2cread, p2cwrite,
  719. c2pread, c2pwrite,
  720. errread, errwrite)
  721. def _make_inheritable(self, handle):
  722. """Return a duplicate of handle, which is inheritable"""
  723. return DuplicateHandle(GetCurrentProcess(),
  724. handle, GetCurrentProcess(), 0, 1,
  725. DUPLICATE_SAME_ACCESS)
  726. def _find_w9xpopen(self):
  727. """Find and return absolute path to w9xpopen.exe"""
  728. w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
  729. "w9xpopen.exe")
  730. if not os.path.exists(w9xpopen):
  731. # Eeek - file-not-found - possibly an embedding
  732. # situation - see if we can locate it in sys.exec_prefix
  733. w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
  734. "w9xpopen.exe")
  735. if not os.path.exists(w9xpopen):
  736. raise RuntimeError("Cannot locate w9xpopen.exe, which is "
  737. "needed for Popen to work with your "
  738. "shell or platform.")
  739. return w9xpopen
  740. def _execute_child(self, args, executable, preexec_fn, close_fds,
  741. pass_fds, cwd, env, universal_newlines,
  742. startupinfo, creationflags, shell,
  743. p2cread, p2cwrite,
  744. c2pread, c2pwrite,
  745. errread, errwrite,
  746. unused_restore_signals, unused_start_new_session):
  747. """Execute program (MS Windows version)"""
  748. assert not pass_fds, "pass_fds not supported on Windows."
  749. if not isinstance(args, string_types):
  750. args = list2cmdline(args)
  751. # Process startup details
  752. if startupinfo is None:
  753. startupinfo = STARTUPINFO()
  754. if None not in (p2cread, c2pwrite, errwrite):
  755. startupinfo.dwFlags |= STARTF_USESTDHANDLES
  756. startupinfo.hStdInput = p2cread
  757. startupinfo.hStdOutput = c2pwrite
  758. startupinfo.hStdError = errwrite
  759. if shell:
  760. startupinfo.dwFlags |= STARTF_USESHOWWINDOW
  761. startupinfo.wShowWindow = SW_HIDE
  762. comspec = os.environ.get("COMSPEC", "cmd.exe")
  763. args = '{} /c "{}"'.format(comspec, args)
  764. if GetVersion() >= 0x80000000 or os.path.basename(comspec).lower() == "command.com":
  765. # Win9x, or using command.com on NT. We need to
  766. # use the w9xpopen intermediate program. For more
  767. # information, see KB Q150956
  768. # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
  769. w9xpopen = self._find_w9xpopen()
  770. args = '"%s" %s' % (w9xpopen, args)
  771. # Not passing CREATE_NEW_CONSOLE has been known to
  772. # cause random failures on win9x. Specifically a
  773. # dialog: "Your program accessed mem currently in
  774. # use at xxx" and a hopeful warning about the
  775. # stability of your system. Cost is Ctrl+C wont
  776. # kill children.
  777. creationflags |= CREATE_NEW_CONSOLE
  778. # Start the process
  779. try:
  780. hp, ht, pid, tid = CreateProcess(executable, args,
  781. # no special security
  782. None, None,
  783. int(not close_fds),
  784. creationflags,
  785. env,
  786. cwd,
  787. startupinfo)
  788. except IOError as e: # From 2.6 on, pywintypes.error was defined as IOError
  789. # Translate pywintypes.error to WindowsError, which is
  790. # a subclass of OSError. FIXME: We should really
  791. # translate errno using _sys_errlist (or similar), but
  792. # how can this be done from Python?
  793. if PY3:
  794. raise # don't remap here
  795. raise WindowsError(*e.args)
  796. finally:
  797. # Child is launched. Close the parent's copy of those pipe
  798. # handles that only the child should have open. You need
  799. # to make sure that no handles to the write end of the
  800. # output pipe are maintained in this process or else the
  801. # pipe will not close when the child process exits and the
  802. # ReadFile will hang.
  803. def _close(x):
  804. if x is not None and x != -1:
  805. if hasattr(x, 'Close'):
  806. x.Close()
  807. else:
  808. _winapi.CloseHandle(x)
  809. _close(p2cread)
  810. _close(c2pwrite)
  811. _close(errwrite)
  812. if hasattr(self, '_devnull'):
  813. os.close(self._devnull)
  814. # Retain the process handle, but close the thread handle
  815. self._child_created = True
  816. self._handle = Handle(hp) if not hasattr(hp, 'Close') else hp
  817. self.pid = pid
  818. _winapi.CloseHandle(ht) if not hasattr(ht, 'Close') else ht.Close()
  819. def _internal_poll(self):
  820. """Check if child process has terminated. Returns returncode
  821. attribute.
  822. """
  823. if self.returncode is None:
  824. if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
  825. self.returncode = GetExitCodeProcess(self._handle)
  826. self.result.set(self.returncode)
  827. return self.returncode
  828. def rawlink(self, callback):
  829. if not self.result.ready() and not self._waiting:
  830. self._waiting = True
  831. Greenlet.spawn(self._wait)
  832. self.result.rawlink(linkproxy(callback, self))
  833. # XXX unlink
  834. def _blocking_wait(self):
  835. WaitForSingleObject(self._handle, INFINITE)
  836. self.returncode = GetExitCodeProcess(self._handle)
  837. return self.returncode
  838. def _wait(self):
  839. self.threadpool.spawn(self._blocking_wait).rawlink(self.result)
  840. def wait(self, timeout=None, _raise_exc=PY3):
  841. """Wait for child process to terminate. Returns returncode
  842. attribute."""
  843. if self.returncode is None:
  844. if not self._waiting:
  845. self._waiting = True
  846. self._wait()
  847. return self._gevent_result_wait(timeout, _raise_exc)
  848. def send_signal(self, sig):
  849. """Send a signal to the process
  850. """
  851. if sig == signal.SIGTERM:
  852. self.terminate()
  853. elif sig == signal.CTRL_C_EVENT:
  854. os.kill(self.pid, signal.CTRL_C_EVENT)
  855. elif sig == signal.CTRL_BREAK_EVENT:
  856. os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  857. else:
  858. raise ValueError("Unsupported signal: {}".format(sig))
  859. def terminate(self):
  860. """Terminates the process
  861. """
  862. TerminateProcess(self._handle, 1)
  863. kill = terminate
  864. else:
  865. #
  866. # POSIX methods
  867. #
  868. def rawlink(self, callback):
  869. # Not public documented, part of the link protocol
  870. self.result.rawlink(linkproxy(callback, self))
  871. # XXX unlink
  872. def _get_handles(self, stdin, stdout, stderr):
  873. """Construct and return tuple with IO objects:
  874. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  875. """
  876. p2cread, p2cwrite = None, None
  877. c2pread, c2pwrite = None, None
  878. errread, errwrite = None, None
  879. try:
  880. DEVNULL
  881. except NameError:
  882. _devnull = object()
  883. else:
  884. _devnull = DEVNULL
  885. if stdin is None:
  886. pass
  887. elif stdin == PIPE:
  888. p2cread, p2cwrite = self.pipe_cloexec()
  889. elif stdin == _devnull:
  890. p2cread = self._get_devnull()
  891. elif isinstance(stdin, int):
  892. p2cread = stdin
  893. else:
  894. # Assuming file-like object
  895. p2cread = stdin.fileno()
  896. if stdout is None:
  897. pass
  898. elif stdout == PIPE:
  899. c2pread, c2pwrite = self.pipe_cloexec()
  900. elif stdout == _devnull:
  901. c2pwrite = self._get_devnull()
  902. elif isinstance(stdout, int):
  903. c2pwrite = stdout
  904. else:
  905. # Assuming file-like object
  906. c2pwrite = stdout.fileno()
  907. if stderr is None:
  908. pass
  909. elif stderr == PIPE:
  910. errread, errwrite = self.pipe_cloexec()
  911. elif stderr == STDOUT:
  912. errwrite = c2pwrite
  913. elif stderr == _devnull:
  914. errwrite = self._get_devnull()
  915. elif isinstance(stderr, int):
  916. errwrite = stderr
  917. else:
  918. # Assuming file-like object
  919. errwrite = stderr.fileno()
  920. return (p2cread, p2cwrite,
  921. c2pread, c2pwrite,
  922. errread, errwrite)
  923. def _set_cloexec_flag(self, fd, cloexec=True):
  924. try:
  925. cloexec_flag = fcntl.FD_CLOEXEC
  926. except AttributeError:
  927. cloexec_flag = 1
  928. old = fcntl.fcntl(fd, fcntl.F_GETFD)
  929. if cloexec:
  930. fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  931. else:
  932. fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
  933. def _remove_nonblock_flag(self, fd):
  934. flags = fcntl.fcntl(fd, fcntl.F_GETFL) & (~os.O_NONBLOCK)
  935. fcntl.fcntl(fd, fcntl.F_SETFL, flags)
  936. def pipe_cloexec(self):
  937. """Create a pipe with FDs set CLOEXEC."""
  938. # Pipes' FDs are set CLOEXEC by default because we don't want them
  939. # to be inherited by other subprocesses: the CLOEXEC flag is removed
  940. # from the child's FDs by _dup2(), between fork() and exec().
  941. # This is not atomic: we would need the pipe2() syscall for that.
  942. r, w = os.pipe()
  943. self._set_cloexec_flag(r)
  944. self._set_cloexec_flag(w)
  945. return r, w
  946. def _close_fds(self, keep):
  947. # `keep` is a set of fds, so we
  948. # use os.closerange from 3 to min(keep)
  949. # and then from max(keep + 1) to MAXFD and
  950. # loop through filling in the gaps.
  951. # Under new python versions, we need to explicitly set
  952. # passed fds to be inheritable or they will go away on exec
  953. if hasattr(os, 'set_inheritable'):
  954. set_inheritable = os.set_inheritable
  955. else:
  956. set_inheritable = lambda i, v: True
  957. if hasattr(os, 'closerange'):
  958. keep = sorted(keep)
  959. min_keep = min(keep)
  960. max_keep = max(keep)
  961. os.closerange(3, min_keep)
  962. os.closerange(max_keep + 1, MAXFD)
  963. for i in xrange(min_keep, max_keep):
  964. if i in keep:
  965. set_inheritable(i, True)
  966. continue
  967. try:
  968. os.close(i)
  969. except:
  970. pass
  971. else:
  972. for i in xrange(3, MAXFD):
  973. if i in keep:
  974. set_inheritable(i, True)
  975. continue
  976. try:
  977. os.close(i)
  978. except:
  979. pass
  980. def _execute_child(self, args, executable, preexec_fn, close_fds,
  981. pass_fds, cwd, env, universal_newlines,
  982. startupinfo, creationflags, shell,
  983. p2cread, p2cwrite,
  984. c2pread, c2pwrite,
  985. errread, errwrite,
  986. restore_signals, start_new_session):
  987. """Execute program (POSIX version)"""
  988. if PY3 and isinstance(args, (str, bytes)):
  989. args = [args]
  990. elif not PY3 and isinstance(args, string_types):
  991. args = [args]
  992. else:
  993. args = list(args)
  994. if shell:
  995. args = ["/bin/sh", "-c"] + args
  996. if executable:
  997. args[0] = executable
  998. if executable is None:
  999. executable = args[0]
  1000. self._loop.install_sigchld()
  1001. # For transferring possible exec failure from child to parent
  1002. # The first char specifies the exception type: 0 means
  1003. # OSError, 1 means some other error.
  1004. errpipe_read, errpipe_write = self.pipe_cloexec()
  1005. # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
  1006. low_fds_to_close = []
  1007. while errpipe_write < 3:
  1008. low_fds_to_close.append(errpipe_write)
  1009. errpipe_write = os.dup(errpipe_write)
  1010. for low_fd in low_fds_to_close:
  1011. os.close(low_fd)
  1012. try:
  1013. try:
  1014. gc_was_enabled = gc.isenabled()
  1015. # Disable gc to avoid bug where gc -> file_dealloc ->
  1016. # write to stderr -> hang. http://bugs.python.org/issue1336
  1017. gc.disable()
  1018. try:
  1019. self.pid = fork_and_watch(self._on_child, self._loop, True, fork)
  1020. except:
  1021. if gc_was_enabled:
  1022. gc.enable()
  1023. raise
  1024. if self.pid == 0:
  1025. # Child
  1026. try:
  1027. # Close parent's pipe ends
  1028. if p2cwrite is not None:
  1029. os.close(p2cwrite)
  1030. if c2pread is not None:
  1031. os.close(c2pread)
  1032. if errread is not None:
  1033. os.close(errread)
  1034. os.close(errpipe_read)
  1035. # When duping fds, if there arises a situation
  1036. # where one of the fds is either 0, 1 or 2, it
  1037. # is possible that it is overwritten (#12607).
  1038. if c2pwrite == 0:
  1039. c2pwrite = os.dup(c2pwrite)
  1040. if errwrite == 0 or errwrite == 1:
  1041. errwrite = os.dup(errwrite)
  1042. # Dup fds for child
  1043. def _dup2(a, b):
  1044. # dup2() removes the CLOEXEC flag but
  1045. # we must do it ourselves if dup2()
  1046. # would be a no-op (issue #10806).
  1047. if a == b:
  1048. self._set_cloexec_flag(a, False)
  1049. elif a is not None:
  1050. os.dup2(a, b)
  1051. self._remove_nonblock_flag(b)
  1052. _dup2(p2cread, 0)
  1053. _dup2(c2pwrite, 1)
  1054. _dup2(errwrite, 2)
  1055. # Close pipe fds. Make sure we don't close the
  1056. # same fd more than once, or standard fds.
  1057. closed = set([None])
  1058. for fd in [p2cread, c2pwrite, errwrite]:
  1059. if fd not in closed and fd > 2:
  1060. os.close(fd)
  1061. closed.add(fd)
  1062. if cwd is not None:
  1063. os.chdir(cwd)
  1064. if preexec_fn:
  1065. preexec_fn()
  1066. # Close all other fds, if asked for. This must be done
  1067. # after preexec_fn runs.
  1068. if close_fds:
  1069. fds_to_keep = set(pass_fds)
  1070. fds_to_keep.add(errpipe_write)
  1071. self._close_fds(fds_to_keep)
  1072. elif hasattr(os, 'get_inheritable'):
  1073. # close_fds was false, and we're on
  1074. # Python 3.4 or newer, so "all file
  1075. # descriptors except standard streams
  1076. # are closed, and inheritable handles
  1077. # are only inherited if the close_fds
  1078. # parameter is False."
  1079. for i in xrange(3, MAXFD):
  1080. try:
  1081. if i == errpipe_write or os.get_inheritable(i):
  1082. continue
  1083. os.close(i)
  1084. except:
  1085. pass
  1086. if restore_signals:
  1087. # restore the documented signals back to sig_dfl;
  1088. # not all will be defined on every platform
  1089. for sig in 'SIGPIPE', 'SIGXFZ', 'SIGXFSZ':
  1090. sig = getattr(signal, sig, None)
  1091. if sig is not None:
  1092. signal.signal(sig, signal.SIG_DFL)
  1093. if start_new_session:
  1094. os.setsid()
  1095. if env is None:
  1096. os.execvp(executable, args)
  1097. else:
  1098. if PY3:
  1099. # Python 3.6 started testing for
  1100. # bytes values in the env; it also
  1101. # started encoding strs using
  1102. # fsencode and using a lower-level
  1103. # API that takes a list of keys
  1104. # and values. We don't have access
  1105. # to that API, so we go the reverse direction.
  1106. env = {os.fsdecode(k) if isinstance(k, bytes) else k:
  1107. os.fsdecode(v) if isinstance(v, bytes) else v
  1108. for k, v in env.items()}
  1109. os.execvpe(executable, args, env)
  1110. except:
  1111. exc_type, exc_value, tb = sys.exc_info()
  1112. # Save the traceback and attach it to the exception object
  1113. exc_lines = traceback.format_exception(exc_type,
  1114. exc_value,
  1115. tb)
  1116. exc_value.child_traceback = ''.join(exc_lines)
  1117. os.write(errpipe_write, pickle.dumps(exc_value))
  1118. finally:
  1119. # Make sure that the process exits no matter what.
  1120. # The return code does not matter much as it won't be
  1121. # reported to the application
  1122. os._exit(1)
  1123. # Parent
  1124. self._child_created = True
  1125. if gc_was_enabled:
  1126. gc.enable()
  1127. finally:
  1128. # be sure the FD is closed no matter what
  1129. os.close(errpipe_write)
  1130. # self._devnull is not always defined.
  1131. devnull_fd = getattr(self, '_devnull', None)
  1132. if p2cread is not None and p2cwrite is not None and p2cread != devnull_fd:
  1133. os.close(p2cread)
  1134. if c2pwrite is not None and c2pread is not None and c2pwrite != devnull_fd:
  1135. os.close(c2pwrite)
  1136. if errwrite is not None and errread is not None and errwrite != devnull_fd:
  1137. os.close(errwrite)
  1138. if devnull_fd is not None:
  1139. os.close(devnull_fd)
  1140. # Prevent a double close of these fds from __init__ on error.
  1141. self._closed_child_pipe_fds = True
  1142. # Wait for exec to fail or succeed; possibly raising exception
  1143. errpipe_read = FileObject(errpipe_read, 'rb')
  1144. data = errpipe_read.read()
  1145. finally:
  1146. if hasattr(errpipe_read, 'close'):
  1147. errpipe_read.close()
  1148. else:
  1149. os.close(errpipe_read)
  1150. if data != b"":
  1151. self.wait()
  1152. child_exception = pickle.loads(data)
  1153. for fd in (p2cwrite, c2pread, errread):
  1154. if fd is not None:
  1155. os.close(fd)
  1156. raise child_exception
  1157. def _handle_exitstatus(self, sts):
  1158. if os.WIFSIGNALED(sts):
  1159. self.returncode = -os.WTERMSIG(sts)
  1160. elif os.WIFEXITED(sts):
  1161. self.returncode = os.WEXITSTATUS(sts)
  1162. else:
  1163. # Should never happen
  1164. raise RuntimeError("Unknown child exit status!")
  1165. def _internal_poll(self):
  1166. """Check if child process has terminated. Returns returncode
  1167. attribute.
  1168. """
  1169. if self.returncode is None:
  1170. if get_hub() is not getcurrent():
  1171. sig_pending = getattr(self._loop, 'sig_pending', True)
  1172. if sig_pending:
  1173. sleep(0.00001)
  1174. return self.returncode
  1175. def wait(self, timeout=None, _raise_exc=PY3):
  1176. """
  1177. Wait for child process to terminate. Returns :attr:`returncode`
  1178. attribute.
  1179. :keyword timeout: The floating point number of seconds to
  1180. wait. Under Python 2, this is a gevent extension, and
  1181. we simply return if it expires. Under Python 3, if
  1182. this time elapses without finishing the process,
  1183. :exc:`TimeoutExpired` is raised.
  1184. """
  1185. return self._gevent_result_wait(timeout, _raise_exc)
  1186. def send_signal(self, sig):
  1187. """Send a signal to the process
  1188. """
  1189. # Skip signalling a process that we know has already died.
  1190. if self.returncode is None:
  1191. os.kill(self.pid, sig)
  1192. def terminate(self):
  1193. """Terminate the process with SIGTERM
  1194. """
  1195. self.send_signal(signal.SIGTERM)
  1196. def kill(self):
  1197. """Kill the process with SIGKILL
  1198. """
  1199. self.send_signal(signal.SIGKILL)
  1200. def write_and_close(fobj, data):
  1201. try:
  1202. if data:
  1203. fobj.write(data)
  1204. if hasattr(fobj, 'flush'):
  1205. # 3.6 started expecting flush to be called.
  1206. fobj.flush()
  1207. except (OSError, IOError) as ex:
  1208. if ex.errno != errno.EPIPE and ex.errno != errno.EINVAL:
  1209. raise
  1210. finally:
  1211. try:
  1212. fobj.close()
  1213. except EnvironmentError:
  1214. pass
  1215. def _with_stdout_stderr(exc, stderr):
  1216. # Prior to Python 3.5, most exceptions didn't have stdout
  1217. # and stderr attributes and can't take the stderr attribute in their
  1218. # constructor
  1219. exc.stdout = exc.output
  1220. exc.stderr = stderr
  1221. return exc
  1222. class CompletedProcess(object):
  1223. """
  1224. A process that has finished running.
  1225. This is returned by run().
  1226. Attributes:
  1227. - args: The list or str args passed to run().
  1228. - returncode: The exit code of the process, negative for signals.
  1229. - stdout: The standard output (None if not captured).
  1230. - stderr: The standard error (None if not captured).
  1231. .. versionadded:: 1.2a1
  1232. This first appeared in Python 3.5 and is available to all
  1233. Python versions in gevent.
  1234. """
  1235. def __init__(self, args, returncode, stdout=None, stderr=None):
  1236. self.args = args
  1237. self.returncode = returncode
  1238. self.stdout = stdout
  1239. self.stderr = stderr
  1240. def __repr__(self):
  1241. args = ['args={!r}'.format(self.args),
  1242. 'returncode={!r}'.format(self.returncode)]
  1243. if self.stdout is not None:
  1244. args.append('stdout={!r}'.format(self.stdout))
  1245. if self.stderr is not None:
  1246. args.append('stderr={!r}'.format(self.stderr))
  1247. return "{}({})".format(type(self).__name__, ', '.join(args))
  1248. def check_returncode(self):
  1249. """Raise CalledProcessError if the exit code is non-zero."""
  1250. if self.returncode:
  1251. raise _with_stdout_stderr(CalledProcessError(self.returncode, self.args, self.stdout), self.stderr)
  1252. def run(*popenargs, **kwargs):
  1253. """
  1254. run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False) -> CompletedProcess
  1255. Run command with arguments and return a CompletedProcess instance.
  1256. The returned instance will have attributes args, returncode, stdout and
  1257. stderr. By default, stdout and stderr are not captured, and those attributes
  1258. will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
  1259. If check is True and the exit code was non-zero, it raises a
  1260. CalledProcessError. The CalledProcessError object will have the return code
  1261. in the returncode attribute, and output & stderr attributes if those streams
  1262. were captured.
  1263. If timeout is given, and the process takes too long, a TimeoutExpired
  1264. exception will be raised.
  1265. There is an optional argument "input", allowing you to
  1266. pass a string to the subprocess's stdin. If you use this argument
  1267. you may not also use the Popen constructor's "stdin" argument, as
  1268. it will be used internally.
  1269. The other arguments are the same as for the Popen constructor.
  1270. If universal_newlines=True is passed, the "input" argument must be a
  1271. string and stdout/stderr in the returned object will be strings rather than
  1272. bytes.
  1273. .. versionadded:: 1.2a1
  1274. This function first appeared in Python 3.5. It is available on all Python
  1275. versions gevent supports.
  1276. """
  1277. input = kwargs.pop('input', None)
  1278. timeout = kwargs.pop('timeout', None)
  1279. check = kwargs.pop('check', False)
  1280. if input is not None:
  1281. if 'stdin' in kwargs:
  1282. raise ValueError('stdin and input arguments may not both be used.')
  1283. kwargs['stdin'] = PIPE
  1284. with Popen(*popenargs, **kwargs) as process:
  1285. try:
  1286. stdout, stderr = process.communicate(input, timeout=timeout)
  1287. except TimeoutExpired:
  1288. process.kill()
  1289. stdout, stderr = process.communicate()
  1290. raise _with_stdout_stderr(TimeoutExpired(process.args, timeout, output=stdout), stderr)
  1291. except:
  1292. process.kill()
  1293. process.wait()
  1294. raise
  1295. retcode = process.poll()
  1296. if check and retcode:
  1297. raise _with_stdout_stderr(CalledProcessError(retcode, process.args, stdout), stderr)
  1298. return CompletedProcess(process.args, retcode, stdout, stderr)