blob: 809e59f5eb7d0a05efc278d2a06edb947ec2d501 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001# subprocess - Subprocesses with accessible I/O streams
2#
Tim Peterse718f612004-10-12 21:51:32 +00003# For more information about this module, see PEP 324.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004#
Peter Astrand3a708df2005-09-23 17:37:29 +00005# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006#
Peter Astrand69bf13f2005-02-14 08:56:32 +00007# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +00008# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009
Martin Panter4afdca02016-10-25 22:20:48 +000010r"""Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000012This module allows you to spawn processes, connect to their
Martin Panter4afdca02016-10-25 22:20:48 +000013input/output/error pipes, and obtain their return codes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014
Martin Panter4afdca02016-10-25 22:20:48 +000015For a complete description of this module see the Python documentation.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000016
Martin Panter4afdca02016-10-25 22:20:48 +000017Main API
18========
19run(...): Runs a command, waits for it to complete, then returns a
20 CompletedProcess instance.
21Popen(...): A class for flexibly executing a command in a new process
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000022
Martin Panter4afdca02016-10-25 22:20:48 +000023Constants
24---------
25DEVNULL: Special value that indicates that os.devnull should be used
26PIPE: Special value that indicates a pipe should be created
27STDOUT: Special value that indicates that stderr should go to stdout
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000028
29
Martin Panter4afdca02016-10-25 22:20:48 +000030Older API
31=========
32call(...): Runs a command, waits for it to complete, then returns
33 the return code.
34check_call(...): Same as call() but raises CalledProcessError()
35 if return code is not 0
36check_output(...): Same as check_call() but returns the contents of
37 stdout instead of a return code
38getoutput(...): Runs a command in the shell, waits for it to complete,
39 then returns the output
40getstatusoutput(...): Runs a command in the shell, waits for it to complete,
41 then returns a (status, output) tuple
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042"""
43
44import sys
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -070045_mswindows = (sys.platform == "win32")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000046
Guido van Rossumfa0054a2007-05-24 04:05:35 +000047import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000048import os
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040049import time
Christian Heimesa342c012008-04-20 21:01:16 +000050import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000051import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +000052import warnings
Ross Lagerwall4f61b022011-04-05 15:34:00 +020053import errno
Victor Stinnerae586492014-09-02 23:18:25 +020054from time import monotonic as _time
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000055
Peter Astrand454f7672005-01-01 09:36:35 +000056# Exception classes used by this module.
Gregory P. Smith54d412e2011-03-14 14:08:43 -040057class SubprocessError(Exception): pass
58
59
60class CalledProcessError(SubprocessError):
Martin Panter4afdca02016-10-25 22:20:48 +000061 """Raised when run() is called with check=True and the process
62 returns a non-zero exit status.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +000063
Martin Panter4afdca02016-10-25 22:20:48 +000064 Attributes:
65 cmd, returncode, stdout, stderr, output
Georg Brandlf9734072008-12-07 15:30:06 +000066 """
Gregory P. Smith6e730002015-04-14 16:14:25 -070067 def __init__(self, returncode, cmd, output=None, stderr=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068 self.returncode = returncode
69 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +000070 self.output = output
Gregory P. Smith6e730002015-04-14 16:14:25 -070071 self.stderr = stderr
72
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073 def __str__(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +000074 if self.returncode and self.returncode < 0:
75 try:
76 return "Command '%s' died with %r." % (
77 self.cmd, signal.Signals(-self.returncode))
78 except ValueError:
79 return "Command '%s' died with unknown signal %d." % (
80 self.cmd, -self.returncode)
81 else:
82 return "Command '%s' returned non-zero exit status %d." % (
83 self.cmd, self.returncode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Gregory P. Smith6e730002015-04-14 16:14:25 -070085 @property
86 def stdout(self):
87 """Alias for output attribute, to match stderr"""
88 return self.output
89
90 @stdout.setter
91 def stdout(self, value):
92 # There's no obvious reason to set this, but allow it anyway so
93 # .stdout is a transparent alias for .output
94 self.output = value
95
Peter Astrand454f7672005-01-01 09:36:35 +000096
Gregory P. Smith54d412e2011-03-14 14:08:43 -040097class TimeoutExpired(SubprocessError):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040098 """This exception is raised when the timeout expires while waiting for a
99 child process.
Martin Panter4afdca02016-10-25 22:20:48 +0000100
101 Attributes:
102 cmd, output, stdout, stderr, timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400103 """
Gregory P. Smith6e730002015-04-14 16:14:25 -0700104 def __init__(self, cmd, timeout, output=None, stderr=None):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400105 self.cmd = cmd
Reid Kleckner2b228f02011-03-16 16:57:54 -0400106 self.timeout = timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400107 self.output = output
Gregory P. Smith6e730002015-04-14 16:14:25 -0700108 self.stderr = stderr
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400109
110 def __str__(self):
111 return ("Command '%s' timed out after %s seconds" %
112 (self.cmd, self.timeout))
113
Gregory P. Smith6e730002015-04-14 16:14:25 -0700114 @property
115 def stdout(self):
116 return self.output
117
118 @stdout.setter
119 def stdout(self, value):
120 # There's no obvious reason to set this, but allow it anyway so
121 # .stdout is a transparent alias for .output
122 self.output = value
123
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400124
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700125if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126 import threading
127 import msvcrt
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200128 import _winapi
Brian Curtin1ce6b582010-04-24 16:19:22 +0000129 class STARTUPINFO:
130 dwFlags = 0
131 hStdInput = None
132 hStdOutput = None
133 hStdError = None
134 wShowWindow = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -0700136 import _posixsubprocess
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100137 import select
138 import selectors
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700139 try:
140 import threading
141 except ImportError:
142 import dummy_threading as threading
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000143
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000144 # When select or poll has indicated that the file is writable,
145 # we can write up to _PIPE_BUF bytes without risk of blocking.
146 # POSIX defines PIPE_BUF as >= 512.
147 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
148
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100149 # poll/select have the advantage of not requiring any extra file
150 # descriptor, contrarily to epoll/kqueue (also, they require a single
151 # syscall).
152 if hasattr(selectors, 'PollSelector'):
153 _PopenSelector = selectors.PollSelector
154 else:
155 _PopenSelector = selectors.SelectSelector
156
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000157
Brett Cannona23810f2008-05-26 19:04:21 +0000158__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Gregory P. Smith6e730002015-04-14 16:14:25 -0700159 "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL",
160 "SubprocessError", "TimeoutExpired", "CompletedProcess"]
Gregory P. Smithace55862015-04-07 15:57:54 -0700161 # NOTE: We intentionally exclude list2cmdline as it is
162 # considered an internal implementation detail. issue10838.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700164if _mswindows:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200165 from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
166 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
167 STD_ERROR_HANDLE, SW_HIDE,
168 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Brian Curtin5d9deaa2011-04-29 16:24:07 -0500169
Brian Curtin08fd8d92011-04-29 16:11:30 -0500170 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500171 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
172 "STD_ERROR_HANDLE", "SW_HIDE",
Martin Panter528619b2016-04-16 23:42:37 +0000173 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW",
174 "STARTUPINFO"])
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200175
176 class Handle(int):
177 closed = False
178
179 def Close(self, CloseHandle=_winapi.CloseHandle):
180 if not self.closed:
181 self.closed = True
182 CloseHandle(self)
183
184 def Detach(self):
185 if not self.closed:
186 self.closed = True
187 return int(self)
188 raise ValueError("already closed")
189
190 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300191 return "%s(%d)" % (self.__class__.__name__, int(self))
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200192
193 __del__ = Close
194 __str__ = __repr__
195
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200197# This lists holds Popen instances for which the underlying process had not
198# exited at the time its __del__ method got called: those processes are wait()ed
199# for synchronously from _cleanup() when a new Popen object is created, to avoid
200# zombie processes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201_active = []
202
203def _cleanup():
204 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000205 res = inst._internal_poll(_deadstate=sys.maxsize)
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200206 if res is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207 try:
208 _active.remove(inst)
209 except ValueError:
210 # This can happen if two threads create a new Popen instance.
211 # It's harmless that it was already removed, so ignore.
212 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213
214PIPE = -1
215STDOUT = -2
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200216DEVNULL = -3
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217
218
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200219# XXX This function is only used by multiprocessing and the test suite,
220# but it's here so that it can be imported when Python is compiled without
221# threads.
222
Victor Stinner9def2842016-01-18 12:15:08 +0100223def _optim_args_from_interpreter_flags():
224 """Return a list of command-line arguments reproducing the current
225 optimization settings in sys.flags."""
226 args = []
227 value = sys.flags.optimize
228 if value > 0:
229 args.append('-' + 'O' * value)
230 return args
231
232
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200233def _args_from_interpreter_flags():
234 """Return a list of command-line arguments reproducing the current
235 settings in sys.flags and sys.warnoptions."""
236 flag_opt_map = {
237 'debug': 'd',
238 # 'inspect': 'i',
239 # 'interactive': 'i',
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200240 'dont_write_bytecode': 'B',
241 'no_user_site': 's',
242 'no_site': 'S',
243 'ignore_environment': 'E',
244 'verbose': 'v',
245 'bytes_warning': 'b',
246 'quiet': 'q',
Victor Stinner9def2842016-01-18 12:15:08 +0100247 # -O is handled in _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200248 }
Victor Stinner9def2842016-01-18 12:15:08 +0100249 args = _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200250 for flag, opt in flag_opt_map.items():
251 v = getattr(sys.flags, flag)
252 if v > 0:
253 args.append('-' + opt * v)
254 for opt in sys.warnoptions:
255 args.append('-W' + opt)
256 return args
257
258
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400259def call(*popenargs, timeout=None, **kwargs):
260 """Run command with arguments. Wait for command to complete or
261 timeout, then return the returncode attribute.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262
263 The arguments are the same as for the Popen constructor. Example:
264
265 retcode = call(["ls", "-l"])
266 """
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200267 with Popen(*popenargs, **kwargs) as p:
268 try:
269 return p.wait(timeout=timeout)
270 except:
271 p.kill()
272 p.wait()
273 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
275
Peter Astrand454f7672005-01-01 09:36:35 +0000276def check_call(*popenargs, **kwargs):
277 """Run command with arguments. Wait for command to complete. If
278 the exit code was zero then return, otherwise raise
279 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000280 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000281
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400282 The arguments are the same as for the call function. Example:
Peter Astrand454f7672005-01-01 09:36:35 +0000283
284 check_call(["ls", "-l"])
285 """
286 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000287 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000288 cmd = kwargs.get("args")
289 if cmd is None:
290 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000291 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000292 return 0
293
294
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400295def check_output(*popenargs, timeout=None, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700296 r"""Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000297
298 If the exit code was non-zero it raises a CalledProcessError. The
299 CalledProcessError object will have the return code in the returncode
300 attribute and output in the output attribute.
301
302 The arguments are the same as for the Popen constructor. Example:
303
304 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000305 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000306
307 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000308 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000309
310 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000311 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000312 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000313 b'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith91110f52013-03-19 23:25:16 -0700314
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300315 There is an additional optional argument, "input", allowing you to
316 pass a string to the subprocess's stdin. If you use this argument
317 you may not also use the Popen constructor's "stdin" argument, as
318 it too will be used internally. Example:
319
320 >>> check_output(["sed", "-e", "s/foo/bar/"],
321 ... input=b"when in the course of fooman events\n")
322 b'when in the course of barman events\n'
323
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400324 If universal_newlines=True is passed, the "input" argument must be a
325 string and the return value will be a string rather than bytes.
Georg Brandlf9734072008-12-07 15:30:06 +0000326 """
327 if 'stdout' in kwargs:
328 raise ValueError('stdout argument not allowed, it will be overridden.')
Gregory P. Smith6e730002015-04-14 16:14:25 -0700329
330 if 'input' in kwargs and kwargs['input'] is None:
331 # Explicitly passing input=None was previously equivalent to passing an
332 # empty string. That is maintained here for backwards compatibility.
333 kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''
334
335 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
336 **kwargs).stdout
337
338
339class CompletedProcess(object):
340 """A process that has finished running.
341
342 This is returned by run().
343
344 Attributes:
345 args: The list or str args passed to run().
346 returncode: The exit code of the process, negative for signals.
347 stdout: The standard output (None if not captured).
348 stderr: The standard error (None if not captured).
349 """
350 def __init__(self, args, returncode, stdout=None, stderr=None):
351 self.args = args
352 self.returncode = returncode
353 self.stdout = stdout
354 self.stderr = stderr
355
356 def __repr__(self):
357 args = ['args={!r}'.format(self.args),
358 'returncode={!r}'.format(self.returncode)]
359 if self.stdout is not None:
360 args.append('stdout={!r}'.format(self.stdout))
361 if self.stderr is not None:
362 args.append('stderr={!r}'.format(self.stderr))
363 return "{}({})".format(type(self).__name__, ', '.join(args))
364
365 def check_returncode(self):
366 """Raise CalledProcessError if the exit code is non-zero."""
367 if self.returncode:
368 raise CalledProcessError(self.returncode, self.args, self.stdout,
369 self.stderr)
370
371
372def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
373 """Run command with arguments and return a CompletedProcess instance.
374
375 The returned instance will have attributes args, returncode, stdout and
376 stderr. By default, stdout and stderr are not captured, and those attributes
377 will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
378
379 If check is True and the exit code was non-zero, it raises a
380 CalledProcessError. The CalledProcessError object will have the return code
381 in the returncode attribute, and output & stderr attributes if those streams
382 were captured.
383
384 If timeout is given, and the process takes too long, a TimeoutExpired
385 exception will be raised.
386
387 There is an optional argument "input", allowing you to
388 pass a string to the subprocess's stdin. If you use this argument
389 you may not also use the Popen constructor's "stdin" argument, as
390 it will be used internally.
391
392 The other arguments are the same as for the Popen constructor.
393
394 If universal_newlines=True is passed, the "input" argument must be a
395 string and stdout/stderr in the returned object will be strings rather than
396 bytes.
397 """
398 if input is not None:
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300399 if 'stdin' in kwargs:
400 raise ValueError('stdin and input arguments may not both be used.')
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300401 kwargs['stdin'] = PIPE
Gregory P. Smith6e730002015-04-14 16:14:25 -0700402
403 with Popen(*popenargs, **kwargs) as process:
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200404 try:
Gregory P. Smith6e730002015-04-14 16:14:25 -0700405 stdout, stderr = process.communicate(input, timeout=timeout)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200406 except TimeoutExpired:
407 process.kill()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700408 stdout, stderr = process.communicate()
409 raise TimeoutExpired(process.args, timeout, output=stdout,
410 stderr=stderr)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200411 except:
412 process.kill()
413 process.wait()
414 raise
415 retcode = process.poll()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700416 if check and retcode:
417 raise CalledProcessError(retcode, process.args,
418 output=stdout, stderr=stderr)
419 return CompletedProcess(process.args, retcode, stdout, stderr)
Peter Astrand454f7672005-01-01 09:36:35 +0000420
421
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422def list2cmdline(seq):
423 """
424 Translate a sequence of arguments into a command line
425 string, using the same rules as the MS C runtime:
426
427 1) Arguments are delimited by white space, which is either a
428 space or a tab.
429
430 2) A string surrounded by double quotation marks is
431 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000432 contained within. A quoted string can be embedded in an
433 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434
435 3) A double quotation mark preceded by a backslash is
436 interpreted as a literal double quotation mark.
437
438 4) Backslashes are interpreted literally, unless they
439 immediately precede a double quotation mark.
440
441 5) If backslashes immediately precede a double quotation mark,
442 every pair of backslashes is interpreted as a literal
443 backslash. If the number of backslashes is odd, the last
444 backslash escapes the next double quotation mark as
445 described in rule 3.
446 """
447
448 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000449 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
450 # or search http://msdn.microsoft.com for
451 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 result = []
453 needquote = False
454 for arg in seq:
455 bs_buf = []
456
457 # Add a space to separate this argument from the others
458 if result:
459 result.append(' ')
460
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000461 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 if needquote:
463 result.append('"')
464
465 for c in arg:
466 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000467 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 bs_buf.append(c)
469 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000470 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 result.append('\\' * len(bs_buf)*2)
472 bs_buf = []
473 result.append('\\"')
474 else:
475 # Normal char
476 if bs_buf:
477 result.extend(bs_buf)
478 bs_buf = []
479 result.append(c)
480
Christian Heimesfdab48e2008-01-20 09:06:41 +0000481 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 if bs_buf:
483 result.extend(bs_buf)
484
485 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000486 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 result.append('"')
488
489 return ''.join(result)
490
491
Brett Cannona23810f2008-05-26 19:04:21 +0000492# Various tools for executing commands and looking at their output and status.
493#
Brett Cannona23810f2008-05-26 19:04:21 +0000494
495def getstatusoutput(cmd):
Tim Golden60798142013-11-05 12:57:25 +0000496 """ Return (status, output) of executing cmd in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000497
Tim Golden60798142013-11-05 12:57:25 +0000498 Execute the string 'cmd' in a shell with 'check_output' and
Steve Dower050acae2016-09-06 20:16:17 -0700499 return a 2-tuple (status, output). The locale encoding is used
500 to decode the output and process newlines.
Tim Golden60798142013-11-05 12:57:25 +0000501
502 A trailing newline is stripped from the output.
503 The exit status for the command can be interpreted
504 according to the rules for the function 'wait'. Example:
Brett Cannona23810f2008-05-26 19:04:21 +0000505
506 >>> import subprocess
507 >>> subprocess.getstatusoutput('ls /bin/ls')
508 (0, '/bin/ls')
509 >>> subprocess.getstatusoutput('cat /bin/junk')
510 (256, 'cat: /bin/junk: No such file or directory')
511 >>> subprocess.getstatusoutput('/bin/junk')
512 (256, 'sh: /bin/junk: not found')
513 """
Tim Goldene0041752013-11-03 12:53:17 +0000514 try:
515 data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
516 status = 0
517 except CalledProcessError as ex:
518 data = ex.output
519 status = ex.returncode
520 if data[-1:] == '\n':
521 data = data[:-1]
522 return status, data
Brett Cannona23810f2008-05-26 19:04:21 +0000523
524def getoutput(cmd):
525 """Return output (stdout or stderr) of executing cmd in a shell.
526
527 Like getstatusoutput(), except the exit status is ignored and the return
528 value is a string containing the command's output. Example:
529
530 >>> import subprocess
531 >>> subprocess.getoutput('ls /bin/ls')
532 '/bin/ls'
533 """
534 return getstatusoutput(cmd)[1]
535
536
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000537_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000538
539
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540class Popen(object):
Martin Panter4afdca02016-10-25 22:20:48 +0000541 """ Execute a child program in a new process.
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200542
Martin Panter4afdca02016-10-25 22:20:48 +0000543 For a complete description of the arguments see the Python documentation.
544
545 Arguments:
546 args: A string, or a sequence of program arguments.
547
548 bufsize: supplied as the buffering argument to the open() function when
549 creating the stdin/stdout/stderr pipe file objects
550
551 executable: A replacement program to execute.
552
553 stdin, stdout and stderr: These specify the executed programs' standard
554 input, standard output and standard error file handles, respectively.
555
556 preexec_fn: (POSIX only) An object to be called in the child process
557 just before the child is executed.
558
559 close_fds: Controls closing or inheriting of file descriptors.
560
561 shell: If true, the command will be executed through the shell.
562
563 cwd: Sets the current directory before the child is executed.
564
565 env: Defines the environment variables for the new process.
566
567 universal_newlines: If true, use universal line endings for file
568 objects stdin, stdout and stderr.
569
570 startupinfo and creationflags (Windows only)
571
572 restore_signals (POSIX only)
573
574 start_new_session (POSIX only)
575
576 pass_fds (POSIX only)
577
Martin Panter3dca6242016-10-25 23:41:42 +0000578 encoding and errors: Text mode encoding and error handling to use for
579 file objects stdin, stdout and stderr.
580
Martin Panter4afdca02016-10-25 22:20:48 +0000581 Attributes:
582 stdin, stdout, stderr, pid, returncode
583 """
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200584 _child_created = False # Set here since __del__ checks it
585
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700586 def __init__(self, args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000588 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
589 shell=False, cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000590 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000591 restore_signals=True, start_new_session=False,
Steve Dower050acae2016-09-06 20:16:17 -0700592 pass_fds=(), *, encoding=None, errors=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 """Create new Popen instance."""
594 _cleanup()
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700595 # Held while anything is calling waitpid before returncode has been
596 # updated to prevent clobbering returncode if wait() or poll() are
597 # called from multiple threads at once. After acquiring the lock,
598 # code must re-check self.returncode to see if another thread just
599 # finished a waitpid() call.
600 self._waitpid_lock = threading.Lock()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400602 self._input = None
603 self._communication_started = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000604 if bufsize is None:
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700605 bufsize = -1 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000606 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000607 raise TypeError("bufsize must be an integer")
608
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700609 if _mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000610 if preexec_fn is not None:
611 raise ValueError("preexec_fn is not supported on Windows "
612 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000613 any_stdio_set = (stdin is not None or stdout is not None or
614 stderr is not None)
615 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
616 if any_stdio_set:
617 close_fds = False
618 else:
619 close_fds = True
620 elif close_fds and any_stdio_set:
621 raise ValueError(
622 "close_fds is not supported on Windows platforms"
623 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 else:
625 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000626 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
627 close_fds = True
628 if pass_fds and not close_fds:
629 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
630 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000631 if startupinfo is not None:
632 raise ValueError("startupinfo is only supported on Windows "
633 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000635 raise ValueError("creationflags is only supported on Windows "
636 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400638 self.args = args
Tim Peterse718f612004-10-12 21:51:32 +0000639 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 self.stdout = None
641 self.stderr = None
642 self.pid = None
643 self.returncode = None
644 self.universal_newlines = universal_newlines
Steve Dower050acae2016-09-06 20:16:17 -0700645 self.encoding = encoding
646 self.errors = errors
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
648 # Input and output objects. The general principle is like
649 # this:
650 #
651 # Parent Child
652 # ------ -----
653 # p2cwrite ---stdin---> p2cread
654 # c2pread <--stdout--- c2pwrite
655 # errread <--stderr--- errwrite
656 #
657 # On POSIX, the child objects are file descriptors. On
658 # Windows, these are Windows file handles. The parent objects
659 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000660 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000662
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 (p2cread, p2cwrite,
664 c2pread, c2pwrite,
665 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
666
Antoine Pitrouc9982322011-01-04 19:07:07 +0000667 # We wrap OS handles *before* launching the child, otherwise a
668 # quickly terminating child could make our fds unwrappable
669 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700671 if _mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000672 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000673 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000674 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000675 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000676 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000677 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000678
Steve Dower050acae2016-09-06 20:16:17 -0700679 text_mode = encoding or errors or universal_newlines
Tim Peterse718f612004-10-12 21:51:32 +0000680
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700681 self._closed_child_pipe_fds = False
Steve Dower050acae2016-09-06 20:16:17 -0700682
Antoine Pitrouc9982322011-01-04 19:07:07 +0000683 try:
Steve Dower050acae2016-09-06 20:16:17 -0700684 if p2cwrite != -1:
685 self.stdin = io.open(p2cwrite, 'wb', bufsize)
686 if text_mode:
687 self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
688 line_buffering=(bufsize == 1),
689 encoding=encoding, errors=errors)
690 if c2pread != -1:
691 self.stdout = io.open(c2pread, 'rb', bufsize)
692 if text_mode:
693 self.stdout = io.TextIOWrapper(self.stdout,
694 encoding=encoding, errors=errors)
695 if errread != -1:
696 self.stderr = io.open(errread, 'rb', bufsize)
697 if text_mode:
698 self.stderr = io.TextIOWrapper(self.stderr,
699 encoding=encoding, errors=errors)
700
Antoine Pitrouc9982322011-01-04 19:07:07 +0000701 self._execute_child(args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300702 pass_fds, cwd, env,
Antoine Pitrouc9982322011-01-04 19:07:07 +0000703 startupinfo, creationflags, shell,
704 p2cread, p2cwrite,
705 c2pread, c2pwrite,
706 errread, errwrite,
707 restore_signals, start_new_session)
708 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800709 # Cleanup if the child failed starting.
710 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000711 try:
712 f.close()
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200713 except OSError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800714 pass # Ignore EBADF or other errors.
715
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700716 if not self._closed_child_pipe_fds:
717 to_close = []
718 if stdin == PIPE:
719 to_close.append(p2cread)
720 if stdout == PIPE:
721 to_close.append(c2pwrite)
722 if stderr == PIPE:
723 to_close.append(errwrite)
724 if hasattr(self, '_devnull'):
725 to_close.append(self._devnull)
726 for fd in to_close:
727 try:
728 os.close(fd)
Gregory P. Smith22ba31a2013-06-15 18:14:56 -0700729 except OSError:
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700730 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800731
Antoine Pitrouc9982322011-01-04 19:07:07 +0000732 raise
733
Steve Dower050acae2016-09-06 20:16:17 -0700734 def _translate_newlines(self, data, encoding, errors):
735 data = data.decode(encoding, errors)
Andrew Svetlov82860712012-08-19 22:13:41 +0300736 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737
Brian Curtin79cdb662010-12-03 02:46:02 +0000738 def __enter__(self):
739 return self
740
741 def __exit__(self, type, value, traceback):
742 if self.stdout:
743 self.stdout.close()
744 if self.stderr:
745 self.stderr.close()
Serhiy Storchakaab900c22015-02-28 12:43:08 +0200746 try: # Flushing a BufferedWriter may raise an error
747 if self.stdin:
748 self.stdin.close()
749 finally:
750 # Wait for the process to terminate, to avoid zombies.
751 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200753 def __del__(self, _maxsize=sys.maxsize):
754 if not self._child_created:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 # We didn't get to successfully create a child process.
756 return
Victor Stinner5a48e212016-05-20 12:11:15 +0200757 if self.returncode is None:
Victor Stinnerc206f1e2016-06-14 16:42:59 +0200758 # Not reading subprocess exit status creates a zombi process which
759 # is only destroyed at the parent python process exit
760 warnings.warn("subprocess %s is still running" % self.pid,
761 ResourceWarning, source=self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000763 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000765 # Child is still running, keep us alive until we can wait on it.
766 _active.append(self)
767
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200768 def _get_devnull(self):
769 if not hasattr(self, '_devnull'):
770 self._devnull = os.open(os.devnull, os.O_RDWR)
771 return self._devnull
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000772
Victor Stinnera5e881d2015-01-14 17:07:59 +0100773 def _stdin_write(self, input):
774 if input:
775 try:
776 self.stdin.write(input)
777 except BrokenPipeError:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000778 pass # communicate() must ignore broken pipe errors.
Victor Stinnera5e881d2015-01-14 17:07:59 +0100779 except OSError as e:
780 if e.errno == errno.EINVAL and self.poll() is not None:
781 # Issue #19612: On Windows, stdin.write() fails with EINVAL
782 # if the process already exited before the write
783 pass
784 else:
785 raise
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000786 try:
787 self.stdin.close()
788 except BrokenPipeError:
789 pass # communicate() must ignore broken pipe errors.
790 except OSError as e:
791 if e.errno == errno.EINVAL and self.poll() is not None:
792 pass
793 else:
794 raise
Victor Stinnera5e881d2015-01-14 17:07:59 +0100795
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400796 def communicate(self, input=None, timeout=None):
Peter Astrand23109f02005-03-03 20:28:59 +0000797 """Interact with process: Send data to stdin. Read data from
798 stdout and stderr, until end-of-file is reached. Wait for
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400799 process to terminate.
Tim Peterseba28be2005-03-28 01:08:02 +0000800
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400801 The optional "input" argument should be data to be sent to the
802 child process (if self.universal_newlines is True, this should
803 be a string; if it is False, "input" should be bytes), or
804 None, if no data should be sent to the child.
805
806 communicate() returns a tuple (stdout, stderr). These will be
807 bytes or, if self.universal_newlines was True, a string.
808 """
Peter Astrand23109f02005-03-03 20:28:59 +0000809
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400810 if self._communication_started and input:
811 raise ValueError("Cannot send input after starting communication")
812
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400813 # Optimization: If we are not worried about timeouts, we haven't
814 # started communicating, and we have one or zero pipes, using select()
815 # or threads is unnecessary.
Victor Stinner7a8d0812011-04-05 13:13:08 +0200816 if (timeout is None and not self._communication_started and
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400817 [self.stdin, self.stdout, self.stderr].count(None) >= 2):
Tim Peterseba28be2005-03-28 01:08:02 +0000818 stdout = None
819 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000820 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +0100821 self._stdin_write(input)
Peter Astrand23109f02005-03-03 20:28:59 +0000822 elif self.stdout:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000823 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000824 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000825 elif self.stderr:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000826 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000827 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000828 self.wait()
Victor Stinner7a8d0812011-04-05 13:13:08 +0200829 else:
830 if timeout is not None:
Victor Stinner949d8c92012-05-30 13:30:32 +0200831 endtime = _time() + timeout
Victor Stinner7a8d0812011-04-05 13:13:08 +0200832 else:
833 endtime = None
Tim Peterseba28be2005-03-28 01:08:02 +0000834
Victor Stinner7a8d0812011-04-05 13:13:08 +0200835 try:
836 stdout, stderr = self._communicate(input, endtime, timeout)
837 finally:
838 self._communication_started = True
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400839
Victor Stinner7a8d0812011-04-05 13:13:08 +0200840 sts = self.wait(timeout=self._remaining_time(endtime))
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400841
842 return (stdout, stderr)
Peter Astrand23109f02005-03-03 20:28:59 +0000843
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000845 def poll(self):
Martin Panter4afdca02016-10-25 22:20:48 +0000846 """Check if child process has terminated. Set and return returncode
847 attribute."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000848 return self._internal_poll()
849
850
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400851 def _remaining_time(self, endtime):
852 """Convenience for _communicate when computing timeouts."""
853 if endtime is None:
854 return None
855 else:
Victor Stinner949d8c92012-05-30 13:30:32 +0200856 return endtime - _time()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400857
858
Reid Kleckner2b228f02011-03-16 16:57:54 -0400859 def _check_timeout(self, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400860 """Convenience for checking if a timeout has expired."""
861 if endtime is None:
862 return
Victor Stinner949d8c92012-05-30 13:30:32 +0200863 if _time() > endtime:
Reid Kleckner2b228f02011-03-16 16:57:54 -0400864 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400865
866
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700867 if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 #
869 # Windows methods
870 #
871 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000872 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
874 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000875 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000876 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000877
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000878 p2cread, p2cwrite = -1, -1
879 c2pread, c2pwrite = -1, -1
880 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881
Peter Astrandd38ddf42005-02-10 08:32:50 +0000882 if stdin is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200883 p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000884 if p2cread is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200885 p2cread, _ = _winapi.CreatePipe(None, 0)
886 p2cread = Handle(p2cread)
887 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000888 elif stdin == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200889 p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
890 p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200891 elif stdin == DEVNULL:
892 p2cread = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000893 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894 p2cread = msvcrt.get_osfhandle(stdin)
895 else:
896 # Assuming file-like object
897 p2cread = msvcrt.get_osfhandle(stdin.fileno())
898 p2cread = self._make_inheritable(p2cread)
899
Peter Astrandd38ddf42005-02-10 08:32:50 +0000900 if stdout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200901 c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000902 if c2pwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200903 _, c2pwrite = _winapi.CreatePipe(None, 0)
904 c2pwrite = Handle(c2pwrite)
905 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000906 elif stdout == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200907 c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
908 c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200909 elif stdout == DEVNULL:
910 c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000911 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 c2pwrite = msvcrt.get_osfhandle(stdout)
913 else:
914 # Assuming file-like object
915 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
916 c2pwrite = self._make_inheritable(c2pwrite)
917
Peter Astrandd38ddf42005-02-10 08:32:50 +0000918 if stderr is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200919 errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000920 if errwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200921 _, errwrite = _winapi.CreatePipe(None, 0)
922 errwrite = Handle(errwrite)
923 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000924 elif stderr == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200925 errread, errwrite = _winapi.CreatePipe(None, 0)
926 errread, errwrite = Handle(errread), Handle(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927 elif stderr == STDOUT:
928 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200929 elif stderr == DEVNULL:
930 errwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000931 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 errwrite = msvcrt.get_osfhandle(stderr)
933 else:
934 # Assuming file-like object
935 errwrite = msvcrt.get_osfhandle(stderr.fileno())
936 errwrite = self._make_inheritable(errwrite)
937
938 return (p2cread, p2cwrite,
939 c2pread, c2pwrite,
940 errread, errwrite)
941
942
943 def _make_inheritable(self, handle):
944 """Return a duplicate of handle, which is inheritable"""
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200945 h = _winapi.DuplicateHandle(
946 _winapi.GetCurrentProcess(), handle,
947 _winapi.GetCurrentProcess(), 0, 1,
948 _winapi.DUPLICATE_SAME_ACCESS)
949 return Handle(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950
951
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000952 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300953 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000954 startupinfo, creationflags, shell,
955 p2cread, p2cwrite,
956 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000957 errread, errwrite,
958 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 """Execute program (MS Windows version)"""
960
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000961 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000962
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000963 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 args = list2cmdline(args)
965
Peter Astrandc1d65362004-11-07 14:30:34 +0000966 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000967 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000968 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +0000969 if -1 not in (p2cread, c2pwrite, errwrite):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200970 startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000971 startupinfo.hStdInput = p2cread
972 startupinfo.hStdOutput = c2pwrite
973 startupinfo.hStdError = errwrite
974
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 if shell:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200976 startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
977 startupinfo.wShowWindow = _winapi.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +0000979 args = '{} /c "{}"'.format (comspec, args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000981 # Start the process
982 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200983 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000984 # no special security
985 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000986 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000987 creationflags,
988 env,
989 cwd,
990 startupinfo)
Tim Goldenad537f22010-08-08 11:18:16 +0000991 finally:
992 # Child is launched. Close the parent's copy of those pipe
993 # handles that only the child should have open. You need
994 # to make sure that no handles to the write end of the
995 # output pipe are maintained in this process or else the
996 # pipe will not close when the child process exits and the
997 # ReadFile will hang.
998 if p2cread != -1:
999 p2cread.Close()
1000 if c2pwrite != -1:
1001 c2pwrite.Close()
1002 if errwrite != -1:
1003 errwrite.Close()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001004 if hasattr(self, '_devnull'):
1005 os.close(self._devnull)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006
1007 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001008 self._child_created = True
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001009 self._handle = Handle(hp)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 self.pid = pid
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001011 _winapi.CloseHandle(ht)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012
Brett Cannon84df1e62010-05-14 00:33:40 +00001013 def _internal_poll(self, _deadstate=None,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001014 _WaitForSingleObject=_winapi.WaitForSingleObject,
1015 _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
1016 _GetExitCodeProcess=_winapi.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001017 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001018 attribute.
1019
1020 This method is called by __del__, so it can only refer to objects
1021 in its local scope.
1022
1023 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001024 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001025 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1026 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 return self.returncode
1028
1029
Gregory P. Smith82604e02016-11-20 16:31:07 -08001030 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031 """Wait for child process to terminate. Returns returncode
1032 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001033 if timeout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001034 timeout_millis = _winapi.INFINITE
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001035 else:
Reid Kleckner91156ff2011-03-21 10:06:10 -07001036 timeout_millis = int(timeout * 1000)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001037 if self.returncode is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001038 result = _winapi.WaitForSingleObject(self._handle,
1039 timeout_millis)
1040 if result == _winapi.WAIT_TIMEOUT:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001041 raise TimeoutExpired(self.args, timeout)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001042 self.returncode = _winapi.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043 return self.returncode
1044
1045
1046 def _readerthread(self, fh, buffer):
1047 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001048 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049
1050
Reid Kleckner2b228f02011-03-16 16:57:54 -04001051 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001052 # Start reader threads feeding into a list hanging off of this
1053 # object, unless they've already been started.
1054 if self.stdout and not hasattr(self, "_stdout_buff"):
1055 self._stdout_buff = []
1056 self.stdout_thread = \
1057 threading.Thread(target=self._readerthread,
1058 args=(self.stdout, self._stdout_buff))
1059 self.stdout_thread.daemon = True
1060 self.stdout_thread.start()
1061 if self.stderr and not hasattr(self, "_stderr_buff"):
1062 self._stderr_buff = []
1063 self.stderr_thread = \
1064 threading.Thread(target=self._readerthread,
1065 args=(self.stderr, self._stderr_buff))
1066 self.stderr_thread.daemon = True
1067 self.stderr_thread.start()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068
1069 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +01001070 self._stdin_write(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001072 # Wait for the reader threads, or time out. If we time out, the
1073 # threads remain reading and the fds left open in case the user
1074 # calls communicate again.
1075 if self.stdout is not None:
1076 self.stdout_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001077 if self.stdout_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001078 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001079 if self.stderr is not None:
1080 self.stderr_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001081 if self.stderr_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001082 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001083
1084 # Collect the output from and close both pipes, now that we know
1085 # both have been read successfully.
1086 stdout = None
1087 stderr = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001088 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001089 stdout = self._stdout_buff
1090 self.stdout.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001092 stderr = self._stderr_buff
1093 self.stderr.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094
1095 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001096 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001097 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001098 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099 stderr = stderr[0]
1100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001101 return (stdout, stderr)
1102
Christian Heimesa342c012008-04-20 21:01:16 +00001103 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001104 """Send a signal to the process."""
1105 # Don't signal a process that we know has already died.
1106 if self.returncode is not None:
1107 return
Christian Heimesa342c012008-04-20 21:01:16 +00001108 if sig == signal.SIGTERM:
1109 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001110 elif sig == signal.CTRL_C_EVENT:
1111 os.kill(self.pid, signal.CTRL_C_EVENT)
1112 elif sig == signal.CTRL_BREAK_EVENT:
1113 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001114 else:
Brian Curtin19651362010-09-07 13:24:38 +00001115 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001116
1117 def terminate(self):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001118 """Terminates the process."""
1119 # Don't terminate a process that we know has already died.
1120 if self.returncode is not None:
1121 return
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001122 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001123 _winapi.TerminateProcess(self._handle, 1)
Antoine Pitroub69ef162012-03-11 19:33:29 +01001124 except PermissionError:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001125 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1126 # process already died.
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001127 rc = _winapi.GetExitCodeProcess(self._handle)
1128 if rc == _winapi.STILL_ACTIVE:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001129 raise
1130 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001131
1132 kill = terminate
1133
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 else:
1135 #
1136 # POSIX methods
1137 #
1138 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001139 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1141 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001142 p2cread, p2cwrite = -1, -1
1143 c2pread, c2pwrite = -1, -1
1144 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001145
Peter Astrandd38ddf42005-02-10 08:32:50 +00001146 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001147 pass
1148 elif stdin == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001149 p2cread, p2cwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001150 elif stdin == DEVNULL:
1151 p2cread = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001152 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001153 p2cread = stdin
1154 else:
1155 # Assuming file-like object
1156 p2cread = stdin.fileno()
1157
Peter Astrandd38ddf42005-02-10 08:32:50 +00001158 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001159 pass
1160 elif stdout == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001161 c2pread, c2pwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001162 elif stdout == DEVNULL:
1163 c2pwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001164 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001165 c2pwrite = stdout
1166 else:
1167 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001168 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001169
Peter Astrandd38ddf42005-02-10 08:32:50 +00001170 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 pass
1172 elif stderr == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001173 errread, errwrite = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174 elif stderr == STDOUT:
Martin Panterc7635892016-05-13 01:54:44 +00001175 if c2pwrite != -1:
1176 errwrite = c2pwrite
1177 else: # child's stdout is not set, use parent's stdout
1178 errwrite = sys.__stdout__.fileno()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001179 elif stderr == DEVNULL:
1180 errwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001181 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001182 errwrite = stderr
1183 else:
1184 # Assuming file-like object
1185 errwrite = stderr.fileno()
1186
1187 return (p2cread, p2cwrite,
1188 c2pread, c2pwrite,
1189 errread, errwrite)
1190
1191
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001192 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001193 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001194 startupinfo, creationflags, shell,
1195 p2cread, p2cwrite,
1196 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001197 errread, errwrite,
1198 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001199 """Execute program (POSIX version)"""
1200
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001201 if isinstance(args, (str, bytes)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001202 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 else:
1204 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001205
1206 if shell:
Xavier de Gayeb35fc622016-12-13 16:32:21 +01001207 # On Android the default shell is at '/system/bin/sh'.
1208 unix_shell = ('/system/bin/sh' if
1209 hasattr(sys, 'getandroidapilevel') else '/bin/sh')
1210 args = [unix_shell, "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001211 if executable:
1212 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213
Peter Astrandd38ddf42005-02-10 08:32:50 +00001214 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001215 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001216 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001217
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001218 # For transferring possible exec failure from child to parent.
1219 # Data format: "exception name:hex errno:description"
1220 # Pickle is not used; it is complex and involves memory allocation.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001221 errpipe_read, errpipe_write = os.pipe()
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001222 # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
1223 low_fds_to_close = []
1224 while errpipe_write < 3:
1225 low_fds_to_close.append(errpipe_write)
1226 errpipe_write = os.dup(errpipe_write)
1227 for low_fd in low_fds_to_close:
1228 os.close(low_fd)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001229 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001230 try:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001231 # We must avoid complex work that could involve
1232 # malloc or free in the child process to avoid
1233 # potential deadlocks, thus we do all this here.
1234 # and pass it to fork_exec()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001235
Victor Stinner372b8382011-06-21 17:24:21 +02001236 if env is not None:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001237 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
1238 for k, v in env.items()]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001239 else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001240 env_list = None # Use execv instead of execve.
1241 executable = os.fsencode(executable)
1242 if os.path.dirname(executable):
1243 executable_list = (executable,)
1244 else:
1245 # This matches the behavior of os._execvpe().
1246 executable_list = tuple(
1247 os.path.join(os.fsencode(dir), executable)
1248 for dir in os.get_exec_path(env))
Gregory P. Smith361e30c2013-12-01 00:12:24 -08001249 fds_to_keep = set(pass_fds)
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001250 fds_to_keep.add(errpipe_write)
1251 self.pid = _posixsubprocess.fork_exec(
1252 args, executable_list,
1253 close_fds, sorted(fds_to_keep), cwd, env_list,
1254 p2cread, p2cwrite, c2pread, c2pwrite,
1255 errread, errwrite,
1256 errpipe_read, errpipe_write,
1257 restore_signals, start_new_session, preexec_fn)
Charles-François Natali558639f2011-08-18 19:11:29 +02001258 self._child_created = True
Facundo Batista10706e22009-06-19 20:34:30 +00001259 finally:
1260 # be sure the FD is closed no matter what
1261 os.close(errpipe_write)
1262
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001263 # self._devnull is not always defined.
1264 devnull_fd = getattr(self, '_devnull', None)
1265 if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001266 os.close(p2cread)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001267 if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001268 os.close(c2pwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001269 if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001270 os.close(errwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001271 if devnull_fd is not None:
1272 os.close(devnull_fd)
1273 # Prevent a double close of these fds from __init__ on error.
1274 self._closed_child_pipe_fds = True
Facundo Batista10706e22009-06-19 20:34:30 +00001275
1276 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001277 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001278 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001279 while True:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001280 part = os.read(errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001281 errpipe_data += part
1282 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001283 break
Facundo Batista10706e22009-06-19 20:34:30 +00001284 finally:
1285 # be sure the FD is closed no matter what
1286 os.close(errpipe_read)
1287
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001288 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001289 try:
Victor Stinnera58e2c52016-05-20 12:08:12 +02001290 pid, sts = os.waitpid(self.pid, 0)
1291 if pid == self.pid:
1292 self._handle_exitstatus(sts)
1293 else:
1294 self.returncode = sys.maxsize
Victor Stinnera5e881d2015-01-14 17:07:59 +01001295 except ChildProcessError:
1296 pass
Victor Stinnera58e2c52016-05-20 12:08:12 +02001297
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001298 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001299 exception_name, hex_errno, err_msg = (
1300 errpipe_data.split(b':', 2))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001301 except ValueError:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001302 exception_name = b'SubprocessError'
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001303 hex_errno = b'0'
Gregory P. Smith3aee2222012-11-11 00:04:13 -08001304 err_msg = (b'Bad exception data from child: ' +
1305 repr(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001306 child_exception_type = getattr(
1307 builtins, exception_name.decode('ascii'),
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001308 SubprocessError)
Victor Stinner4d078042010-04-23 19:28:32 +00001309 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001310 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001311 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001312 child_exec_never_called = (err_msg == "noexec")
1313 if child_exec_never_called:
1314 err_msg = ""
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001315 if errno_num != 0:
1316 err_msg = os.strerror(errno_num)
1317 if errno_num == errno.ENOENT:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001318 if child_exec_never_called:
1319 # The error must be from chdir(cwd).
1320 err_msg += ': ' + repr(cwd)
1321 else:
1322 err_msg += ': ' + repr(orig_executable)
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001323 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001324 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001325
1326
Brett Cannon84df1e62010-05-14 00:33:40 +00001327 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1328 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1329 _WEXITSTATUS=os.WEXITSTATUS):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001330 """All callers to this function MUST hold self._waitpid_lock."""
Brett Cannon84df1e62010-05-14 00:33:40 +00001331 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka72e77612014-02-10 19:20:22 +02001332 # refer to anything outside of its local scope.
Brett Cannon84df1e62010-05-14 00:33:40 +00001333 if _WIFSIGNALED(sts):
1334 self.returncode = -_WTERMSIG(sts)
1335 elif _WIFEXITED(sts):
1336 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001337 else:
1338 # Should never happen
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001339 raise SubprocessError("Unknown child exit status!")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001340
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001341
Brett Cannon84df1e62010-05-14 00:33:40 +00001342 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov1d960fe2012-12-24 20:08:53 +02001343 _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001344 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001345 attribute.
1346
1347 This method is called by __del__, so it cannot reference anything
1348 outside of the local scope (nor can any methods it calls).
1349
1350 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001351 if self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001352 if not self._waitpid_lock.acquire(False):
1353 # Something else is busy calling waitpid. Don't allow two
1354 # at once. We know nothing yet.
1355 return None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001356 try:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001357 if self.returncode is not None:
1358 return self.returncode # Another thread waited.
Brett Cannon84df1e62010-05-14 00:33:40 +00001359 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001360 if pid == self.pid:
1361 self._handle_exitstatus(sts)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001362 except OSError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001363 if _deadstate is not None:
1364 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001365 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001366 # This happens if SIGCLD is set to be ignored or
1367 # waiting for child processes has otherwise been
1368 # disabled for our process. This child is dead, we
1369 # can't get the status.
1370 # http://bugs.python.org/issue15756
1371 self.returncode = 0
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001372 finally:
1373 self._waitpid_lock.release()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001374 return self.returncode
1375
1376
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001377 def _try_wait(self, wait_flags):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001378 """All callers to this function MUST hold self._waitpid_lock."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001379 try:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001380 (pid, sts) = os.waitpid(self.pid, wait_flags)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001381 except ChildProcessError:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001382 # This happens if SIGCLD is set to be ignored or waiting
1383 # for child processes has otherwise been disabled for our
1384 # process. This child is dead, we can't get the status.
1385 pid = self.pid
1386 sts = 0
1387 return (pid, sts)
1388
1389
Gregory P. Smith82604e02016-11-20 16:31:07 -08001390 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001391 """Wait for child process to terminate. Returns returncode
1392 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001393 if self.returncode is not None:
1394 return self.returncode
Reid Kleckner2b228f02011-03-16 16:57:54 -04001395
Gregory P. Smith82604e02016-11-20 16:31:07 -08001396 if timeout is not None:
1397 endtime = _time() + timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001398 # Enter a busy loop if we have a timeout. This busy loop was
1399 # cribbed from Lib/threading.py in Thread.wait() at r71065.
1400 delay = 0.0005 # 500 us -> initial delay of 1 ms
1401 while True:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001402 if self._waitpid_lock.acquire(False):
1403 try:
1404 if self.returncode is not None:
1405 break # Another thread waited.
1406 (pid, sts) = self._try_wait(os.WNOHANG)
1407 assert pid == self.pid or pid == 0
1408 if pid == self.pid:
1409 self._handle_exitstatus(sts)
1410 break
1411 finally:
1412 self._waitpid_lock.release()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001413 remaining = self._remaining_time(endtime)
1414 if remaining <= 0:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001415 raise TimeoutExpired(self.args, timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001416 delay = min(delay * 2, remaining, .05)
1417 time.sleep(delay)
Gregory P. Smithf328d792012-11-10 21:06:18 -08001418 else:
1419 while self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001420 with self._waitpid_lock:
1421 if self.returncode is not None:
1422 break # Another thread waited.
1423 (pid, sts) = self._try_wait(0)
1424 # Check the pid and loop as waitpid has been known to
1425 # return 0 even without WNOHANG in odd situations.
1426 # http://bugs.python.org/issue14396.
1427 if pid == self.pid:
1428 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001429 return self.returncode
1430
1431
Reid Kleckner2b228f02011-03-16 16:57:54 -04001432 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001433 if self.stdin and not self._communication_started:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001434 # Flush stdio buffer. This might block, if the user has
1435 # been writing to .stdin in an uncontrolled fashion.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001436 try:
1437 self.stdin.flush()
1438 except BrokenPipeError:
1439 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001440 if not input:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001441 try:
1442 self.stdin.close()
1443 except BrokenPipeError:
1444 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001445
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001446 stdout = None
1447 stderr = None
1448
1449 # Only create this mapping if we haven't already.
1450 if not self._communication_started:
1451 self._fileobj2output = {}
1452 if self.stdout:
1453 self._fileobj2output[self.stdout] = []
1454 if self.stderr:
1455 self._fileobj2output[self.stderr] = []
1456
1457 if self.stdout:
1458 stdout = self._fileobj2output[self.stdout]
1459 if self.stderr:
1460 stderr = self._fileobj2output[self.stderr]
1461
1462 self._save_input(input)
1463
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001464 if self._input:
1465 input_view = memoryview(self._input)
1466
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001467 with _PopenSelector() as selector:
1468 if self.stdin and input:
1469 selector.register(self.stdin, selectors.EVENT_WRITE)
1470 if self.stdout:
1471 selector.register(self.stdout, selectors.EVENT_READ)
1472 if self.stderr:
1473 selector.register(self.stderr, selectors.EVENT_READ)
1474
1475 while selector.get_map():
1476 timeout = self._remaining_time(endtime)
1477 if timeout is not None and timeout < 0:
1478 raise TimeoutExpired(self.args, orig_timeout)
1479
1480 ready = selector.select(timeout)
1481 self._check_timeout(endtime, orig_timeout)
1482
1483 # XXX Rewrite these to use non-blocking I/O on the file
1484 # objects; they are no longer using C stdio!
1485
1486 for key, events in ready:
1487 if key.fileobj is self.stdin:
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001488 chunk = input_view[self._input_offset :
1489 self._input_offset + _PIPE_BUF]
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001490 try:
1491 self._input_offset += os.write(key.fd, chunk)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001492 except BrokenPipeError:
1493 selector.unregister(key.fileobj)
1494 key.fileobj.close()
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001495 else:
1496 if self._input_offset >= len(self._input):
1497 selector.unregister(key.fileobj)
1498 key.fileobj.close()
1499 elif key.fileobj in (self.stdout, self.stderr):
Gregory P. Smith7b83b182013-12-08 10:58:28 -08001500 data = os.read(key.fd, 32768)
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001501 if not data:
1502 selector.unregister(key.fileobj)
1503 key.fileobj.close()
1504 self._fileobj2output[key.fileobj].append(data)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001505
1506 self.wait(timeout=self._remaining_time(endtime))
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001507
1508 # All data exchanged. Translate lists into strings.
1509 if stdout is not None:
1510 stdout = b''.join(stdout)
1511 if stderr is not None:
1512 stderr = b''.join(stderr)
1513
1514 # Translate newlines, if requested.
1515 # This also turns bytes into strings.
Steve Dower050acae2016-09-06 20:16:17 -07001516 if self.encoding or self.errors or self.universal_newlines:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001517 if stdout is not None:
1518 stdout = self._translate_newlines(stdout,
Steve Dower050acae2016-09-06 20:16:17 -07001519 self.stdout.encoding,
1520 self.stdout.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001521 if stderr is not None:
1522 stderr = self._translate_newlines(stderr,
Steve Dower050acae2016-09-06 20:16:17 -07001523 self.stderr.encoding,
1524 self.stderr.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001525
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001526 return (stdout, stderr)
1527
1528
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001529 def _save_input(self, input):
1530 # This method is called from the _communicate_with_*() methods
1531 # so that if we time out while communicating, we can continue
1532 # sending input if we retry.
1533 if self.stdin and self._input is None:
1534 self._input_offset = 0
1535 self._input = input
Steve Dower050acae2016-09-06 20:16:17 -07001536 if input is not None and (
1537 self.encoding or self.errors or self.universal_newlines):
1538 self._input = self._input.encode(self.stdin.encoding,
1539 self.stdin.errors)
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001540
1541
Christian Heimesa342c012008-04-20 21:01:16 +00001542 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001543 """Send a signal to the process."""
1544 # Skip signalling a process that we know has already died.
1545 if self.returncode is None:
1546 os.kill(self.pid, sig)
Christian Heimesa342c012008-04-20 21:01:16 +00001547
1548 def terminate(self):
1549 """Terminate the process with SIGTERM
1550 """
1551 self.send_signal(signal.SIGTERM)
1552
1553 def kill(self):
1554 """Kill the process with SIGKILL
1555 """
1556 self.send_signal(signal.SIGKILL)