blob: 65b4086dc61fc312599b51317649c34cec859890 [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,
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -070041 then returns a (exitcode, 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:
Subhendu Ghoshae160bb2017-02-25 20:29:05 +0530130 def __init__(self, *, dwFlags=0, hStdInput=None, hStdOutput=None,
131 hStdError=None, wShowWindow=0):
132 self.dwFlags = dwFlags
133 self.hStdInput = hStdInput
134 self.hStdOutput = hStdOutput
135 self.hStdError = hStdError
136 self.wShowWindow = wShowWindow
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -0700138 import _posixsubprocess
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100139 import select
140 import selectors
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200141 import threading
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000142
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000143 # When select or poll has indicated that the file is writable,
144 # we can write up to _PIPE_BUF bytes without risk of blocking.
145 # POSIX defines PIPE_BUF as >= 512.
146 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
147
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100148 # poll/select have the advantage of not requiring any extra file
149 # descriptor, contrarily to epoll/kqueue (also, they require a single
150 # syscall).
151 if hasattr(selectors, 'PollSelector'):
152 _PopenSelector = selectors.PollSelector
153 else:
154 _PopenSelector = selectors.SelectSelector
155
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000156
Brett Cannona23810f2008-05-26 19:04:21 +0000157__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Gregory P. Smith6e730002015-04-14 16:14:25 -0700158 "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL",
159 "SubprocessError", "TimeoutExpired", "CompletedProcess"]
Gregory P. Smithace55862015-04-07 15:57:54 -0700160 # NOTE: We intentionally exclude list2cmdline as it is
161 # considered an internal implementation detail. issue10838.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000162
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700163if _mswindows:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200164 from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
165 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
166 STD_ERROR_HANDLE, SW_HIDE,
Jamesb5d9e082017-11-08 14:18:59 +0000167 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW,
168 ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS,
169 HIGH_PRIORITY_CLASS, IDLE_PRIORITY_CLASS,
170 NORMAL_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS,
171 CREATE_NO_WINDOW, DETACHED_PROCESS,
172 CREATE_DEFAULT_ERROR_MODE, CREATE_BREAKAWAY_FROM_JOB)
Brian Curtin5d9deaa2011-04-29 16:24:07 -0500173
Brian Curtin08fd8d92011-04-29 16:11:30 -0500174 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500175 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
176 "STD_ERROR_HANDLE", "SW_HIDE",
Martin Panter528619b2016-04-16 23:42:37 +0000177 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW",
Jamesb5d9e082017-11-08 14:18:59 +0000178 "STARTUPINFO",
179 "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
180 "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
181 "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
182 "CREATE_NO_WINDOW", "DETACHED_PROCESS",
183 "CREATE_DEFAULT_ERROR_MODE", "CREATE_BREAKAWAY_FROM_JOB"])
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200184
185 class Handle(int):
186 closed = False
187
188 def Close(self, CloseHandle=_winapi.CloseHandle):
189 if not self.closed:
190 self.closed = True
191 CloseHandle(self)
192
193 def Detach(self):
194 if not self.closed:
195 self.closed = True
196 return int(self)
197 raise ValueError("already closed")
198
199 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300200 return "%s(%d)" % (self.__class__.__name__, int(self))
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200201
202 __del__ = Close
203 __str__ = __repr__
204
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200206# This lists holds Popen instances for which the underlying process had not
207# exited at the time its __del__ method got called: those processes are wait()ed
208# for synchronously from _cleanup() when a new Popen object is created, to avoid
209# zombie processes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210_active = []
211
212def _cleanup():
213 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000214 res = inst._internal_poll(_deadstate=sys.maxsize)
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200215 if res is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216 try:
217 _active.remove(inst)
218 except ValueError:
219 # This can happen if two threads create a new Popen instance.
220 # It's harmless that it was already removed, so ignore.
221 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222
223PIPE = -1
224STDOUT = -2
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200225DEVNULL = -3
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226
227
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200228# XXX This function is only used by multiprocessing and the test suite,
229# but it's here so that it can be imported when Python is compiled without
230# threads.
231
Victor Stinner9def2842016-01-18 12:15:08 +0100232def _optim_args_from_interpreter_flags():
233 """Return a list of command-line arguments reproducing the current
234 optimization settings in sys.flags."""
235 args = []
236 value = sys.flags.optimize
237 if value > 0:
238 args.append('-' + 'O' * value)
239 return args
240
241
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200242def _args_from_interpreter_flags():
243 """Return a list of command-line arguments reproducing the current
Victor Stinner747f48e2017-12-12 22:59:48 +0100244 settings in sys.flags, sys.warnoptions and sys._xoptions."""
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200245 flag_opt_map = {
246 'debug': 'd',
247 # 'inspect': 'i',
248 # 'interactive': 'i',
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200249 'dont_write_bytecode': 'B',
250 'no_user_site': 's',
251 'no_site': 'S',
252 'ignore_environment': 'E',
253 'verbose': 'v',
254 'bytes_warning': 'b',
255 'quiet': 'q',
Victor Stinner9def2842016-01-18 12:15:08 +0100256 # -O is handled in _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200257 }
Victor Stinner9def2842016-01-18 12:15:08 +0100258 args = _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200259 for flag, opt in flag_opt_map.items():
260 v = getattr(sys.flags, flag)
261 if v > 0:
262 args.append('-' + opt * v)
Victor Stinnerf39b6742017-11-20 15:24:56 -0800263
264 # -W options
Victor Stinner747f48e2017-12-12 22:59:48 +0100265 warnopts = sys.warnoptions[:]
266 bytes_warning = sys.flags.bytes_warning
267 xoptions = getattr(sys, '_xoptions', {})
268 dev_mode = ('dev' in xoptions)
269
270 if bytes_warning > 1:
271 warnopts.remove("error::BytesWarning")
272 elif bytes_warning:
273 warnopts.remove("default::BytesWarning")
274 if dev_mode:
275 warnopts.remove('default')
276 for opt in warnopts:
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200277 args.append('-W' + opt)
Victor Stinnerf39b6742017-11-20 15:24:56 -0800278
279 # -X options
Victor Stinner747f48e2017-12-12 22:59:48 +0100280 if dev_mode:
Victor Stinnerf39b6742017-11-20 15:24:56 -0800281 args.extend(('-X', 'dev'))
282 for opt in ('faulthandler', 'tracemalloc', 'importtime',
Victor Stinner91106cd2017-12-13 12:29:09 +0100283 'showalloccount', 'showrefcount', 'utf8'):
Victor Stinnerf39b6742017-11-20 15:24:56 -0800284 if opt in xoptions:
285 value = xoptions[opt]
286 if value is True:
287 arg = opt
288 else:
289 arg = '%s=%s' % (opt, value)
290 args.extend(('-X', arg))
291
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200292 return args
293
294
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400295def call(*popenargs, timeout=None, **kwargs):
296 """Run command with arguments. Wait for command to complete or
297 timeout, then return the returncode attribute.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298
299 The arguments are the same as for the Popen constructor. Example:
300
301 retcode = call(["ls", "-l"])
302 """
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200303 with Popen(*popenargs, **kwargs) as p:
304 try:
305 return p.wait(timeout=timeout)
306 except:
307 p.kill()
308 p.wait()
309 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310
311
Peter Astrand454f7672005-01-01 09:36:35 +0000312def check_call(*popenargs, **kwargs):
313 """Run command with arguments. Wait for command to complete. If
314 the exit code was zero then return, otherwise raise
315 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000316 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000317
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400318 The arguments are the same as for the call function. Example:
Peter Astrand454f7672005-01-01 09:36:35 +0000319
320 check_call(["ls", "-l"])
321 """
322 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000323 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000324 cmd = kwargs.get("args")
325 if cmd is None:
326 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000327 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000328 return 0
329
330
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400331def check_output(*popenargs, timeout=None, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700332 r"""Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000333
334 If the exit code was non-zero it raises a CalledProcessError. The
335 CalledProcessError object will have the return code in the returncode
336 attribute and output in the output attribute.
337
338 The arguments are the same as for the Popen constructor. Example:
339
340 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000341 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000342
343 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000344 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000345
346 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000347 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000348 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000349 b'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith91110f52013-03-19 23:25:16 -0700350
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300351 There is an additional optional argument, "input", allowing you to
352 pass a string to the subprocess's stdin. If you use this argument
353 you may not also use the Popen constructor's "stdin" argument, as
354 it too will be used internally. Example:
355
356 >>> check_output(["sed", "-e", "s/foo/bar/"],
357 ... input=b"when in the course of fooman events\n")
358 b'when in the course of barman events\n'
359
andyclegg7fed7bd2017-10-23 03:01:19 +0100360 By default, all communication is in bytes, and therefore any "input"
361 should be bytes, and the return value wil be bytes. If in text mode,
362 any "input" should be a string, and the return value will be a string
363 decoded according to locale encoding, or by "encoding" if set. Text mode
364 is triggered by setting any of text, encoding, errors or universal_newlines.
Georg Brandlf9734072008-12-07 15:30:06 +0000365 """
366 if 'stdout' in kwargs:
367 raise ValueError('stdout argument not allowed, it will be overridden.')
Gregory P. Smith6e730002015-04-14 16:14:25 -0700368
369 if 'input' in kwargs and kwargs['input'] is None:
370 # Explicitly passing input=None was previously equivalent to passing an
371 # empty string. That is maintained here for backwards compatibility.
372 kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''
373
374 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
375 **kwargs).stdout
376
377
378class CompletedProcess(object):
379 """A process that has finished running.
380
381 This is returned by run().
382
383 Attributes:
384 args: The list or str args passed to run().
385 returncode: The exit code of the process, negative for signals.
386 stdout: The standard output (None if not captured).
387 stderr: The standard error (None if not captured).
388 """
389 def __init__(self, args, returncode, stdout=None, stderr=None):
390 self.args = args
391 self.returncode = returncode
392 self.stdout = stdout
393 self.stderr = stderr
394
395 def __repr__(self):
396 args = ['args={!r}'.format(self.args),
397 'returncode={!r}'.format(self.returncode)]
398 if self.stdout is not None:
399 args.append('stdout={!r}'.format(self.stdout))
400 if self.stderr is not None:
401 args.append('stderr={!r}'.format(self.stderr))
402 return "{}({})".format(type(self).__name__, ', '.join(args))
403
404 def check_returncode(self):
405 """Raise CalledProcessError if the exit code is non-zero."""
406 if self.returncode:
407 raise CalledProcessError(self.returncode, self.args, self.stdout,
408 self.stderr)
409
410
411def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
412 """Run command with arguments and return a CompletedProcess instance.
413
414 The returned instance will have attributes args, returncode, stdout and
415 stderr. By default, stdout and stderr are not captured, and those attributes
416 will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
417
418 If check is True and the exit code was non-zero, it raises a
419 CalledProcessError. The CalledProcessError object will have the return code
420 in the returncode attribute, and output & stderr attributes if those streams
421 were captured.
422
423 If timeout is given, and the process takes too long, a TimeoutExpired
424 exception will be raised.
425
426 There is an optional argument "input", allowing you to
andyclegg7fed7bd2017-10-23 03:01:19 +0100427 pass bytes or a string to the subprocess's stdin. If you use this argument
Gregory P. Smith6e730002015-04-14 16:14:25 -0700428 you may not also use the Popen constructor's "stdin" argument, as
429 it will be used internally.
430
andyclegg7fed7bd2017-10-23 03:01:19 +0100431 By default, all communication is in bytes, and therefore any "input" should
432 be bytes, and the stdout and stderr will be bytes. If in text mode, any
433 "input" should be a string, and stdout and stderr will be strings decoded
434 according to locale encoding, or by "encoding" if set. Text mode is
435 triggered by setting any of text, encoding, errors or universal_newlines.
Gregory P. Smith6e730002015-04-14 16:14:25 -0700436
andyclegg7fed7bd2017-10-23 03:01:19 +0100437 The other arguments are the same as for the Popen constructor.
Gregory P. Smith6e730002015-04-14 16:14:25 -0700438 """
439 if input is not None:
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300440 if 'stdin' in kwargs:
441 raise ValueError('stdin and input arguments may not both be used.')
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300442 kwargs['stdin'] = PIPE
Gregory P. Smith6e730002015-04-14 16:14:25 -0700443
444 with Popen(*popenargs, **kwargs) as process:
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200445 try:
Gregory P. Smith6e730002015-04-14 16:14:25 -0700446 stdout, stderr = process.communicate(input, timeout=timeout)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200447 except TimeoutExpired:
448 process.kill()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700449 stdout, stderr = process.communicate()
450 raise TimeoutExpired(process.args, timeout, output=stdout,
451 stderr=stderr)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200452 except:
453 process.kill()
454 process.wait()
455 raise
456 retcode = process.poll()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700457 if check and retcode:
458 raise CalledProcessError(retcode, process.args,
459 output=stdout, stderr=stderr)
460 return CompletedProcess(process.args, retcode, stdout, stderr)
Peter Astrand454f7672005-01-01 09:36:35 +0000461
462
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463def list2cmdline(seq):
464 """
465 Translate a sequence of arguments into a command line
466 string, using the same rules as the MS C runtime:
467
468 1) Arguments are delimited by white space, which is either a
469 space or a tab.
470
471 2) A string surrounded by double quotation marks is
472 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000473 contained within. A quoted string can be embedded in an
474 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475
476 3) A double quotation mark preceded by a backslash is
477 interpreted as a literal double quotation mark.
478
479 4) Backslashes are interpreted literally, unless they
480 immediately precede a double quotation mark.
481
482 5) If backslashes immediately precede a double quotation mark,
483 every pair of backslashes is interpreted as a literal
484 backslash. If the number of backslashes is odd, the last
485 backslash escapes the next double quotation mark as
486 described in rule 3.
487 """
488
489 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000490 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
491 # or search http://msdn.microsoft.com for
492 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493 result = []
494 needquote = False
495 for arg in seq:
496 bs_buf = []
497
498 # Add a space to separate this argument from the others
499 if result:
500 result.append(' ')
501
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000502 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 if needquote:
504 result.append('"')
505
506 for c in arg:
507 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000508 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000509 bs_buf.append(c)
510 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000511 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 result.append('\\' * len(bs_buf)*2)
513 bs_buf = []
514 result.append('\\"')
515 else:
516 # Normal char
517 if bs_buf:
518 result.extend(bs_buf)
519 bs_buf = []
520 result.append(c)
521
Christian Heimesfdab48e2008-01-20 09:06:41 +0000522 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 if bs_buf:
524 result.extend(bs_buf)
525
526 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000527 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 result.append('"')
529
530 return ''.join(result)
531
532
Brett Cannona23810f2008-05-26 19:04:21 +0000533# Various tools for executing commands and looking at their output and status.
534#
Brett Cannona23810f2008-05-26 19:04:21 +0000535
536def getstatusoutput(cmd):
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700537 """Return (exitcode, output) of executing cmd in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000538
Tim Golden60798142013-11-05 12:57:25 +0000539 Execute the string 'cmd' in a shell with 'check_output' and
Steve Dower050acae2016-09-06 20:16:17 -0700540 return a 2-tuple (status, output). The locale encoding is used
541 to decode the output and process newlines.
Tim Golden60798142013-11-05 12:57:25 +0000542
543 A trailing newline is stripped from the output.
544 The exit status for the command can be interpreted
545 according to the rules for the function 'wait'. Example:
Brett Cannona23810f2008-05-26 19:04:21 +0000546
547 >>> import subprocess
548 >>> subprocess.getstatusoutput('ls /bin/ls')
549 (0, '/bin/ls')
550 >>> subprocess.getstatusoutput('cat /bin/junk')
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700551 (1, 'cat: /bin/junk: No such file or directory')
Brett Cannona23810f2008-05-26 19:04:21 +0000552 >>> subprocess.getstatusoutput('/bin/junk')
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700553 (127, 'sh: /bin/junk: not found')
554 >>> subprocess.getstatusoutput('/bin/kill $$')
555 (-15, '')
Brett Cannona23810f2008-05-26 19:04:21 +0000556 """
Tim Goldene0041752013-11-03 12:53:17 +0000557 try:
andyclegg7fed7bd2017-10-23 03:01:19 +0100558 data = check_output(cmd, shell=True, text=True, stderr=STDOUT)
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700559 exitcode = 0
Tim Goldene0041752013-11-03 12:53:17 +0000560 except CalledProcessError as ex:
561 data = ex.output
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700562 exitcode = ex.returncode
Tim Goldene0041752013-11-03 12:53:17 +0000563 if data[-1:] == '\n':
564 data = data[:-1]
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700565 return exitcode, data
Brett Cannona23810f2008-05-26 19:04:21 +0000566
567def getoutput(cmd):
568 """Return output (stdout or stderr) of executing cmd in a shell.
569
570 Like getstatusoutput(), except the exit status is ignored and the return
571 value is a string containing the command's output. Example:
572
573 >>> import subprocess
574 >>> subprocess.getoutput('ls /bin/ls')
575 '/bin/ls'
576 """
577 return getstatusoutput(cmd)[1]
578
579
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000580_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000581
582
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583class Popen(object):
Martin Panter4afdca02016-10-25 22:20:48 +0000584 """ Execute a child program in a new process.
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200585
Martin Panter4afdca02016-10-25 22:20:48 +0000586 For a complete description of the arguments see the Python documentation.
587
588 Arguments:
589 args: A string, or a sequence of program arguments.
590
591 bufsize: supplied as the buffering argument to the open() function when
592 creating the stdin/stdout/stderr pipe file objects
593
594 executable: A replacement program to execute.
595
596 stdin, stdout and stderr: These specify the executed programs' standard
597 input, standard output and standard error file handles, respectively.
598
599 preexec_fn: (POSIX only) An object to be called in the child process
600 just before the child is executed.
601
602 close_fds: Controls closing or inheriting of file descriptors.
603
604 shell: If true, the command will be executed through the shell.
605
606 cwd: Sets the current directory before the child is executed.
607
608 env: Defines the environment variables for the new process.
609
andyclegg7fed7bd2017-10-23 03:01:19 +0100610 text: If true, decode stdin, stdout and stderr using the given encoding
611 (if set) or the system default otherwise.
612
613 universal_newlines: Alias of text, provided for backwards compatibility.
Martin Panter4afdca02016-10-25 22:20:48 +0000614
615 startupinfo and creationflags (Windows only)
616
617 restore_signals (POSIX only)
618
619 start_new_session (POSIX only)
620
621 pass_fds (POSIX only)
622
Martin Panter3dca6242016-10-25 23:41:42 +0000623 encoding and errors: Text mode encoding and error handling to use for
624 file objects stdin, stdout and stderr.
625
Martin Panter4afdca02016-10-25 22:20:48 +0000626 Attributes:
627 stdin, stdout, stderr, pid, returncode
628 """
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200629 _child_created = False # Set here since __del__ checks it
630
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700631 def __init__(self, args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000633 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
andyclegg7fed7bd2017-10-23 03:01:19 +0100634 shell=False, cwd=None, env=None, universal_newlines=None,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000635 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000636 restore_signals=True, start_new_session=False,
andyclegg7fed7bd2017-10-23 03:01:19 +0100637 pass_fds=(), *, encoding=None, errors=None, text=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 """Create new Popen instance."""
639 _cleanup()
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700640 # Held while anything is calling waitpid before returncode has been
641 # updated to prevent clobbering returncode if wait() or poll() are
642 # called from multiple threads at once. After acquiring the lock,
643 # code must re-check self.returncode to see if another thread just
644 # finished a waitpid() call.
645 self._waitpid_lock = threading.Lock()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400647 self._input = None
648 self._communication_started = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000649 if bufsize is None:
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700650 bufsize = -1 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000651 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000652 raise TypeError("bufsize must be an integer")
653
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700654 if _mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000655 if preexec_fn is not None:
656 raise ValueError("preexec_fn is not supported on Windows "
657 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000658 any_stdio_set = (stdin is not None or stdout is not None or
659 stderr is not None)
660 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
661 if any_stdio_set:
662 close_fds = False
663 else:
664 close_fds = True
665 elif close_fds and any_stdio_set:
666 raise ValueError(
667 "close_fds is not supported on Windows platforms"
668 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 else:
670 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000671 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
672 close_fds = True
673 if pass_fds and not close_fds:
674 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
675 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000676 if startupinfo is not None:
677 raise ValueError("startupinfo is only supported on Windows "
678 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000680 raise ValueError("creationflags is only supported on Windows "
681 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400683 self.args = args
Tim Peterse718f612004-10-12 21:51:32 +0000684 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 self.stdout = None
686 self.stderr = None
687 self.pid = None
688 self.returncode = None
Steve Dower050acae2016-09-06 20:16:17 -0700689 self.encoding = encoding
690 self.errors = errors
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000691
andyclegg7fed7bd2017-10-23 03:01:19 +0100692 # Validate the combinations of text and universal_newlines
693 if (text is not None and universal_newlines is not None
694 and bool(universal_newlines) != bool(text)):
695 raise SubprocessError('Cannot disambiguate when both text '
696 'and universal_newlines are supplied but '
697 'different. Pass one or the other.')
698
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 # Input and output objects. The general principle is like
700 # this:
701 #
702 # Parent Child
703 # ------ -----
704 # p2cwrite ---stdin---> p2cread
705 # c2pread <--stdout--- c2pwrite
706 # errread <--stderr--- errwrite
707 #
708 # On POSIX, the child objects are file descriptors. On
709 # Windows, these are Windows file handles. The parent objects
710 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000711 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000712 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000713
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 (p2cread, p2cwrite,
715 c2pread, c2pwrite,
716 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
717
Antoine Pitrouc9982322011-01-04 19:07:07 +0000718 # We wrap OS handles *before* launching the child, otherwise a
719 # quickly terminating child could make our fds unwrappable
720 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700722 if _mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000723 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000724 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000725 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000726 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000727 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000728 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000729
andyclegg7fed7bd2017-10-23 03:01:19 +0100730 self.text_mode = encoding or errors or text or universal_newlines
Tim Peterse718f612004-10-12 21:51:32 +0000731
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700732 self._closed_child_pipe_fds = False
Steve Dower050acae2016-09-06 20:16:17 -0700733
Antoine Pitrouc9982322011-01-04 19:07:07 +0000734 try:
Steve Dower050acae2016-09-06 20:16:17 -0700735 if p2cwrite != -1:
736 self.stdin = io.open(p2cwrite, 'wb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100737 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700738 self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
739 line_buffering=(bufsize == 1),
740 encoding=encoding, errors=errors)
741 if c2pread != -1:
742 self.stdout = io.open(c2pread, 'rb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100743 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700744 self.stdout = io.TextIOWrapper(self.stdout,
745 encoding=encoding, errors=errors)
746 if errread != -1:
747 self.stderr = io.open(errread, 'rb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100748 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700749 self.stderr = io.TextIOWrapper(self.stderr,
750 encoding=encoding, errors=errors)
751
Antoine Pitrouc9982322011-01-04 19:07:07 +0000752 self._execute_child(args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300753 pass_fds, cwd, env,
Antoine Pitrouc9982322011-01-04 19:07:07 +0000754 startupinfo, creationflags, shell,
755 p2cread, p2cwrite,
756 c2pread, c2pwrite,
757 errread, errwrite,
758 restore_signals, start_new_session)
759 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800760 # Cleanup if the child failed starting.
761 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000762 try:
763 f.close()
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200764 except OSError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800765 pass # Ignore EBADF or other errors.
766
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700767 if not self._closed_child_pipe_fds:
768 to_close = []
769 if stdin == PIPE:
770 to_close.append(p2cread)
771 if stdout == PIPE:
772 to_close.append(c2pwrite)
773 if stderr == PIPE:
774 to_close.append(errwrite)
775 if hasattr(self, '_devnull'):
776 to_close.append(self._devnull)
777 for fd in to_close:
778 try:
Segev Finer4d385172017-08-18 16:18:13 +0300779 if _mswindows and isinstance(fd, Handle):
780 fd.Close()
781 else:
782 os.close(fd)
Gregory P. Smith22ba31a2013-06-15 18:14:56 -0700783 except OSError:
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700784 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800785
Antoine Pitrouc9982322011-01-04 19:07:07 +0000786 raise
787
andyclegg7fed7bd2017-10-23 03:01:19 +0100788 @property
789 def universal_newlines(self):
790 # universal_newlines as retained as an alias of text_mode for API
luzpaza5293b42017-11-05 07:37:50 -0600791 # compatibility. bpo-31756
andyclegg7fed7bd2017-10-23 03:01:19 +0100792 return self.text_mode
793
794 @universal_newlines.setter
795 def universal_newlines(self, universal_newlines):
796 self.text_mode = bool(universal_newlines)
797
Steve Dower050acae2016-09-06 20:16:17 -0700798 def _translate_newlines(self, data, encoding, errors):
799 data = data.decode(encoding, errors)
Andrew Svetlov82860712012-08-19 22:13:41 +0300800 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801
Brian Curtin79cdb662010-12-03 02:46:02 +0000802 def __enter__(self):
803 return self
804
805 def __exit__(self, type, value, traceback):
806 if self.stdout:
807 self.stdout.close()
808 if self.stderr:
809 self.stderr.close()
Serhiy Storchakaab900c22015-02-28 12:43:08 +0200810 try: # Flushing a BufferedWriter may raise an error
811 if self.stdin:
812 self.stdin.close()
813 finally:
814 # Wait for the process to terminate, to avoid zombies.
815 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000816
Victor Stinner9505b032017-01-06 10:44:44 +0100817 def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200818 if not self._child_created:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000819 # We didn't get to successfully create a child process.
820 return
Victor Stinner5a48e212016-05-20 12:11:15 +0200821 if self.returncode is None:
Victor Stinnerc206f1e2016-06-14 16:42:59 +0200822 # Not reading subprocess exit status creates a zombi process which
823 # is only destroyed at the parent python process exit
Victor Stinner9505b032017-01-06 10:44:44 +0100824 _warn("subprocess %s is still running" % self.pid,
825 ResourceWarning, source=self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000827 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829 # Child is still running, keep us alive until we can wait on it.
830 _active.append(self)
831
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200832 def _get_devnull(self):
833 if not hasattr(self, '_devnull'):
834 self._devnull = os.open(os.devnull, os.O_RDWR)
835 return self._devnull
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836
Victor Stinnera5e881d2015-01-14 17:07:59 +0100837 def _stdin_write(self, input):
838 if input:
839 try:
840 self.stdin.write(input)
841 except BrokenPipeError:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000842 pass # communicate() must ignore broken pipe errors.
Victor Stinnerd52aa312017-06-08 17:30:39 +0200843 except OSError as exc:
844 if exc.errno == errno.EINVAL:
845 # bpo-19612, bpo-30418: On Windows, stdin.write() fails
846 # with EINVAL if the child process exited or if the child
847 # process is still running but closed the pipe.
Victor Stinnera5e881d2015-01-14 17:07:59 +0100848 pass
849 else:
850 raise
Victor Stinnerd52aa312017-06-08 17:30:39 +0200851
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000852 try:
853 self.stdin.close()
854 except BrokenPipeError:
855 pass # communicate() must ignore broken pipe errors.
Victor Stinnerd52aa312017-06-08 17:30:39 +0200856 except OSError as exc:
857 if exc.errno == errno.EINVAL:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000858 pass
859 else:
860 raise
Victor Stinnera5e881d2015-01-14 17:07:59 +0100861
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400862 def communicate(self, input=None, timeout=None):
Joel Schaerer88031a92017-09-13 21:11:20 +0200863 """Interact with process: Send data to stdin and close it.
864 Read data from stdout and stderr, until end-of-file is
865 reached. Wait for process to terminate.
Tim Peterseba28be2005-03-28 01:08:02 +0000866
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400867 The optional "input" argument should be data to be sent to the
andyclegg7fed7bd2017-10-23 03:01:19 +0100868 child process, or None, if no data should be sent to the child.
869 communicate() returns a tuple (stdout, stderr).
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400870
andyclegg7fed7bd2017-10-23 03:01:19 +0100871 By default, all communication is in bytes, and therefore any
872 "input" should be bytes, and the (stdout, stderr) will be bytes.
873 If in text mode (indicated by self.text_mode), any "input" should
874 be a string, and (stdout, stderr) will be strings decoded
875 according to locale encoding, or by "encoding" if set. Text mode
876 is triggered by setting any of text, encoding, errors or
877 universal_newlines.
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400878 """
Peter Astrand23109f02005-03-03 20:28:59 +0000879
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400880 if self._communication_started and input:
881 raise ValueError("Cannot send input after starting communication")
882
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400883 # Optimization: If we are not worried about timeouts, we haven't
884 # started communicating, and we have one or zero pipes, using select()
885 # or threads is unnecessary.
Victor Stinner7a8d0812011-04-05 13:13:08 +0200886 if (timeout is None and not self._communication_started and
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400887 [self.stdin, self.stdout, self.stderr].count(None) >= 2):
Tim Peterseba28be2005-03-28 01:08:02 +0000888 stdout = None
889 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000890 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +0100891 self._stdin_write(input)
Peter Astrand23109f02005-03-03 20:28:59 +0000892 elif self.stdout:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000893 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000894 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000895 elif self.stderr:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000896 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000897 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000898 self.wait()
Victor Stinner7a8d0812011-04-05 13:13:08 +0200899 else:
900 if timeout is not None:
Victor Stinner949d8c92012-05-30 13:30:32 +0200901 endtime = _time() + timeout
Victor Stinner7a8d0812011-04-05 13:13:08 +0200902 else:
903 endtime = None
Tim Peterseba28be2005-03-28 01:08:02 +0000904
Victor Stinner7a8d0812011-04-05 13:13:08 +0200905 try:
906 stdout, stderr = self._communicate(input, endtime, timeout)
907 finally:
908 self._communication_started = True
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400909
Victor Stinner7a8d0812011-04-05 13:13:08 +0200910 sts = self.wait(timeout=self._remaining_time(endtime))
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400911
912 return (stdout, stderr)
Peter Astrand23109f02005-03-03 20:28:59 +0000913
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000915 def poll(self):
Martin Panter4afdca02016-10-25 22:20:48 +0000916 """Check if child process has terminated. Set and return returncode
917 attribute."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000918 return self._internal_poll()
919
920
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400921 def _remaining_time(self, endtime):
922 """Convenience for _communicate when computing timeouts."""
923 if endtime is None:
924 return None
925 else:
Victor Stinner949d8c92012-05-30 13:30:32 +0200926 return endtime - _time()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400927
928
Reid Kleckner2b228f02011-03-16 16:57:54 -0400929 def _check_timeout(self, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400930 """Convenience for checking if a timeout has expired."""
931 if endtime is None:
932 return
Victor Stinner949d8c92012-05-30 13:30:32 +0200933 if _time() > endtime:
Reid Kleckner2b228f02011-03-16 16:57:54 -0400934 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400935
936
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700937 if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938 #
939 # Windows methods
940 #
941 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000942 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
944 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000945 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000946 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000947
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000948 p2cread, p2cwrite = -1, -1
949 c2pread, c2pwrite = -1, -1
950 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951
Peter Astrandd38ddf42005-02-10 08:32:50 +0000952 if stdin is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200953 p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000954 if p2cread is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200955 p2cread, _ = _winapi.CreatePipe(None, 0)
956 p2cread = Handle(p2cread)
957 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000958 elif stdin == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200959 p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
960 p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200961 elif stdin == DEVNULL:
962 p2cread = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000963 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 p2cread = msvcrt.get_osfhandle(stdin)
965 else:
966 # Assuming file-like object
967 p2cread = msvcrt.get_osfhandle(stdin.fileno())
968 p2cread = self._make_inheritable(p2cread)
969
Peter Astrandd38ddf42005-02-10 08:32:50 +0000970 if stdout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200971 c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000972 if c2pwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200973 _, c2pwrite = _winapi.CreatePipe(None, 0)
974 c2pwrite = Handle(c2pwrite)
975 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000976 elif stdout == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200977 c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
978 c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200979 elif stdout == DEVNULL:
980 c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000981 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 c2pwrite = msvcrt.get_osfhandle(stdout)
983 else:
984 # Assuming file-like object
985 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
986 c2pwrite = self._make_inheritable(c2pwrite)
987
Peter Astrandd38ddf42005-02-10 08:32:50 +0000988 if stderr is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200989 errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000990 if errwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200991 _, errwrite = _winapi.CreatePipe(None, 0)
992 errwrite = Handle(errwrite)
993 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000994 elif stderr == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200995 errread, errwrite = _winapi.CreatePipe(None, 0)
996 errread, errwrite = Handle(errread), Handle(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 elif stderr == STDOUT:
998 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200999 elif stderr == DEVNULL:
1000 errwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001001 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 errwrite = msvcrt.get_osfhandle(stderr)
1003 else:
1004 # Assuming file-like object
1005 errwrite = msvcrt.get_osfhandle(stderr.fileno())
1006 errwrite = self._make_inheritable(errwrite)
1007
1008 return (p2cread, p2cwrite,
1009 c2pread, c2pwrite,
1010 errread, errwrite)
1011
1012
1013 def _make_inheritable(self, handle):
1014 """Return a duplicate of handle, which is inheritable"""
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001015 h = _winapi.DuplicateHandle(
1016 _winapi.GetCurrentProcess(), handle,
1017 _winapi.GetCurrentProcess(), 0, 1,
1018 _winapi.DUPLICATE_SAME_ACCESS)
1019 return Handle(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020
1021
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001023 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024 startupinfo, creationflags, shell,
1025 p2cread, p2cwrite,
1026 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001027 errread, errwrite,
1028 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029 """Execute program (MS Windows version)"""
1030
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001031 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001032
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001033 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034 args = list2cmdline(args)
1035
Peter Astrandc1d65362004-11-07 14:30:34 +00001036 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +00001037 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001038 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +00001039 if -1 not in (p2cread, c2pwrite, errwrite):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001040 startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +00001041 startupinfo.hStdInput = p2cread
1042 startupinfo.hStdOutput = c2pwrite
1043 startupinfo.hStdError = errwrite
1044
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001045 if shell:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001046 startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
1047 startupinfo.wShowWindow = _winapi.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001048 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +00001049 args = '{} /c "{}"'.format (comspec, args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001050
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051 # Start the process
1052 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001053 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +00001054 # no special security
1055 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001056 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +00001057 creationflags,
1058 env,
Benjamin Petersoncb90f262017-03-02 00:03:41 -08001059 os.fspath(cwd) if cwd is not None else None,
Tim Peterse8374a52004-10-13 03:15:00 +00001060 startupinfo)
Tim Goldenad537f22010-08-08 11:18:16 +00001061 finally:
1062 # Child is launched. Close the parent's copy of those pipe
1063 # handles that only the child should have open. You need
1064 # to make sure that no handles to the write end of the
1065 # output pipe are maintained in this process or else the
1066 # pipe will not close when the child process exits and the
1067 # ReadFile will hang.
1068 if p2cread != -1:
1069 p2cread.Close()
1070 if c2pwrite != -1:
1071 c2pwrite.Close()
1072 if errwrite != -1:
1073 errwrite.Close()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001074 if hasattr(self, '_devnull'):
1075 os.close(self._devnull)
Segev Finer4d385172017-08-18 16:18:13 +03001076 # Prevent a double close of these handles/fds from __init__
1077 # on error.
1078 self._closed_child_pipe_fds = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001079
1080 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001081 self._child_created = True
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001082 self._handle = Handle(hp)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 self.pid = pid
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001084 _winapi.CloseHandle(ht)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085
Brett Cannon84df1e62010-05-14 00:33:40 +00001086 def _internal_poll(self, _deadstate=None,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001087 _WaitForSingleObject=_winapi.WaitForSingleObject,
1088 _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
1089 _GetExitCodeProcess=_winapi.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001091 attribute.
1092
1093 This method is called by __del__, so it can only refer to objects
1094 in its local scope.
1095
1096 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001097 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001098 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1099 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100 return self.returncode
1101
1102
Gregory P. Smith82604e02016-11-20 16:31:07 -08001103 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 """Wait for child process to terminate. Returns returncode
1105 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001106 if timeout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001107 timeout_millis = _winapi.INFINITE
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001108 else:
Reid Kleckner91156ff2011-03-21 10:06:10 -07001109 timeout_millis = int(timeout * 1000)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001110 if self.returncode is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001111 result = _winapi.WaitForSingleObject(self._handle,
1112 timeout_millis)
1113 if result == _winapi.WAIT_TIMEOUT:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001114 raise TimeoutExpired(self.args, timeout)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001115 self.returncode = _winapi.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001116 return self.returncode
1117
1118
1119 def _readerthread(self, fh, buffer):
1120 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001121 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122
1123
Reid Kleckner2b228f02011-03-16 16:57:54 -04001124 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001125 # Start reader threads feeding into a list hanging off of this
1126 # object, unless they've already been started.
1127 if self.stdout and not hasattr(self, "_stdout_buff"):
1128 self._stdout_buff = []
1129 self.stdout_thread = \
1130 threading.Thread(target=self._readerthread,
1131 args=(self.stdout, self._stdout_buff))
1132 self.stdout_thread.daemon = True
1133 self.stdout_thread.start()
1134 if self.stderr and not hasattr(self, "_stderr_buff"):
1135 self._stderr_buff = []
1136 self.stderr_thread = \
1137 threading.Thread(target=self._readerthread,
1138 args=(self.stderr, self._stderr_buff))
1139 self.stderr_thread.daemon = True
1140 self.stderr_thread.start()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001141
1142 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +01001143 self._stdin_write(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001144
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001145 # Wait for the reader threads, or time out. If we time out, the
1146 # threads remain reading and the fds left open in case the user
1147 # calls communicate again.
1148 if self.stdout is not None:
1149 self.stdout_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001150 if self.stdout_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001151 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001152 if self.stderr is not None:
1153 self.stderr_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001154 if self.stderr_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001155 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001156
1157 # Collect the output from and close both pipes, now that we know
1158 # both have been read successfully.
1159 stdout = None
1160 stderr = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001162 stdout = self._stdout_buff
1163 self.stdout.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001165 stderr = self._stderr_buff
1166 self.stderr.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001167
1168 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001169 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001170 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001171 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001172 stderr = stderr[0]
1173
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174 return (stdout, stderr)
1175
Christian Heimesa342c012008-04-20 21:01:16 +00001176 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001177 """Send a signal to the process."""
1178 # Don't signal a process that we know has already died.
1179 if self.returncode is not None:
1180 return
Christian Heimesa342c012008-04-20 21:01:16 +00001181 if sig == signal.SIGTERM:
1182 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001183 elif sig == signal.CTRL_C_EVENT:
1184 os.kill(self.pid, signal.CTRL_C_EVENT)
1185 elif sig == signal.CTRL_BREAK_EVENT:
1186 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001187 else:
Brian Curtin19651362010-09-07 13:24:38 +00001188 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001189
1190 def terminate(self):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001191 """Terminates the process."""
1192 # Don't terminate a process that we know has already died.
1193 if self.returncode is not None:
1194 return
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001195 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001196 _winapi.TerminateProcess(self._handle, 1)
Antoine Pitroub69ef162012-03-11 19:33:29 +01001197 except PermissionError:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001198 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1199 # process already died.
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001200 rc = _winapi.GetExitCodeProcess(self._handle)
1201 if rc == _winapi.STILL_ACTIVE:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001202 raise
1203 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001204
1205 kill = terminate
1206
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001207 else:
1208 #
1209 # POSIX methods
1210 #
1211 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001212 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1214 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001215 p2cread, p2cwrite = -1, -1
1216 c2pread, c2pwrite = -1, -1
1217 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001218
Peter Astrandd38ddf42005-02-10 08:32:50 +00001219 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001220 pass
1221 elif stdin == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001222 p2cread, p2cwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001223 elif stdin == DEVNULL:
1224 p2cread = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001225 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001226 p2cread = stdin
1227 else:
1228 # Assuming file-like object
1229 p2cread = stdin.fileno()
1230
Peter Astrandd38ddf42005-02-10 08:32:50 +00001231 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001232 pass
1233 elif stdout == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001234 c2pread, c2pwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001235 elif stdout == DEVNULL:
1236 c2pwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001237 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001238 c2pwrite = stdout
1239 else:
1240 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001241 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001242
Peter Astrandd38ddf42005-02-10 08:32:50 +00001243 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001244 pass
1245 elif stderr == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001246 errread, errwrite = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001247 elif stderr == STDOUT:
Martin Panterc7635892016-05-13 01:54:44 +00001248 if c2pwrite != -1:
1249 errwrite = c2pwrite
1250 else: # child's stdout is not set, use parent's stdout
1251 errwrite = sys.__stdout__.fileno()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001252 elif stderr == DEVNULL:
1253 errwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001254 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001255 errwrite = stderr
1256 else:
1257 # Assuming file-like object
1258 errwrite = stderr.fileno()
1259
1260 return (p2cread, p2cwrite,
1261 c2pread, c2pwrite,
1262 errread, errwrite)
1263
1264
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001265 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001266 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001267 startupinfo, creationflags, shell,
1268 p2cread, p2cwrite,
1269 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001270 errread, errwrite,
1271 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001272 """Execute program (POSIX version)"""
1273
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001274 if isinstance(args, (str, bytes)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001275 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001276 else:
1277 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001278
1279 if shell:
Xavier de Gayeb35fc622016-12-13 16:32:21 +01001280 # On Android the default shell is at '/system/bin/sh'.
1281 unix_shell = ('/system/bin/sh' if
1282 hasattr(sys, 'getandroidapilevel') else '/bin/sh')
1283 args = [unix_shell, "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001284 if executable:
1285 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001286
Peter Astrandd38ddf42005-02-10 08:32:50 +00001287 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001288 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001289 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001290
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001291 # For transferring possible exec failure from child to parent.
1292 # Data format: "exception name:hex errno:description"
1293 # Pickle is not used; it is complex and involves memory allocation.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001294 errpipe_read, errpipe_write = os.pipe()
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001295 # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
1296 low_fds_to_close = []
1297 while errpipe_write < 3:
1298 low_fds_to_close.append(errpipe_write)
1299 errpipe_write = os.dup(errpipe_write)
1300 for low_fd in low_fds_to_close:
1301 os.close(low_fd)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001302 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001303 try:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001304 # We must avoid complex work that could involve
1305 # malloc or free in the child process to avoid
1306 # potential deadlocks, thus we do all this here.
1307 # and pass it to fork_exec()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001308
Victor Stinner372b8382011-06-21 17:24:21 +02001309 if env is not None:
Serhiy Storchakad174d242017-06-23 19:39:27 +03001310 env_list = []
1311 for k, v in env.items():
1312 k = os.fsencode(k)
1313 if b'=' in k:
1314 raise ValueError("illegal environment variable name")
1315 env_list.append(k + b'=' + os.fsencode(v))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001316 else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001317 env_list = None # Use execv instead of execve.
1318 executable = os.fsencode(executable)
1319 if os.path.dirname(executable):
1320 executable_list = (executable,)
1321 else:
1322 # This matches the behavior of os._execvpe().
1323 executable_list = tuple(
1324 os.path.join(os.fsencode(dir), executable)
1325 for dir in os.get_exec_path(env))
Gregory P. Smith361e30c2013-12-01 00:12:24 -08001326 fds_to_keep = set(pass_fds)
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001327 fds_to_keep.add(errpipe_write)
1328 self.pid = _posixsubprocess.fork_exec(
1329 args, executable_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03001330 close_fds, tuple(sorted(map(int, fds_to_keep))),
1331 cwd, env_list,
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001332 p2cread, p2cwrite, c2pread, c2pwrite,
1333 errread, errwrite,
1334 errpipe_read, errpipe_write,
1335 restore_signals, start_new_session, preexec_fn)
Charles-François Natali558639f2011-08-18 19:11:29 +02001336 self._child_created = True
Facundo Batista10706e22009-06-19 20:34:30 +00001337 finally:
1338 # be sure the FD is closed no matter what
1339 os.close(errpipe_write)
1340
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001341 # self._devnull is not always defined.
1342 devnull_fd = getattr(self, '_devnull', None)
1343 if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001344 os.close(p2cread)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001345 if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001346 os.close(c2pwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001347 if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001348 os.close(errwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001349 if devnull_fd is not None:
1350 os.close(devnull_fd)
1351 # Prevent a double close of these fds from __init__ on error.
1352 self._closed_child_pipe_fds = True
Facundo Batista10706e22009-06-19 20:34:30 +00001353
1354 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001355 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001356 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001357 while True:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001358 part = os.read(errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001359 errpipe_data += part
1360 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001361 break
Facundo Batista10706e22009-06-19 20:34:30 +00001362 finally:
1363 # be sure the FD is closed no matter what
1364 os.close(errpipe_read)
1365
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001366 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001367 try:
Victor Stinnera58e2c52016-05-20 12:08:12 +02001368 pid, sts = os.waitpid(self.pid, 0)
1369 if pid == self.pid:
1370 self._handle_exitstatus(sts)
1371 else:
1372 self.returncode = sys.maxsize
Victor Stinnera5e881d2015-01-14 17:07:59 +01001373 except ChildProcessError:
1374 pass
Victor Stinnera58e2c52016-05-20 12:08:12 +02001375
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001376 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001377 exception_name, hex_errno, err_msg = (
1378 errpipe_data.split(b':', 2))
Ammar Askar3fc499b2017-09-06 02:41:30 -04001379 # The encoding here should match the encoding
1380 # written in by the subprocess implementations
1381 # like _posixsubprocess
1382 err_msg = err_msg.decode()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001383 except ValueError:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001384 exception_name = b'SubprocessError'
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001385 hex_errno = b'0'
Ammar Askar3fc499b2017-09-06 02:41:30 -04001386 err_msg = 'Bad exception data from child: {!r}'.format(
1387 bytes(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001388 child_exception_type = getattr(
1389 builtins, exception_name.decode('ascii'),
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001390 SubprocessError)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001391 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001392 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001393 child_exec_never_called = (err_msg == "noexec")
1394 if child_exec_never_called:
1395 err_msg = ""
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001396 # The error must be from chdir(cwd).
1397 err_filename = cwd
1398 else:
1399 err_filename = orig_executable
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001400 if errno_num != 0:
1401 err_msg = os.strerror(errno_num)
1402 if errno_num == errno.ENOENT:
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001403 err_msg += ': ' + repr(err_filename)
1404 raise child_exception_type(errno_num, err_msg, err_filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001405 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001406
1407
Brett Cannon84df1e62010-05-14 00:33:40 +00001408 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1409 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
Gregory P. Smith50e16e32017-01-22 17:28:38 -08001410 _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED,
1411 _WSTOPSIG=os.WSTOPSIG):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001412 """All callers to this function MUST hold self._waitpid_lock."""
Brett Cannon84df1e62010-05-14 00:33:40 +00001413 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka72e77612014-02-10 19:20:22 +02001414 # refer to anything outside of its local scope.
Brett Cannon84df1e62010-05-14 00:33:40 +00001415 if _WIFSIGNALED(sts):
1416 self.returncode = -_WTERMSIG(sts)
1417 elif _WIFEXITED(sts):
1418 self.returncode = _WEXITSTATUS(sts)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08001419 elif _WIFSTOPPED(sts):
1420 self.returncode = -_WSTOPSIG(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001421 else:
1422 # Should never happen
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001423 raise SubprocessError("Unknown child exit status!")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001424
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001425
Brett Cannon84df1e62010-05-14 00:33:40 +00001426 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov1d960fe2012-12-24 20:08:53 +02001427 _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001428 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001429 attribute.
1430
1431 This method is called by __del__, so it cannot reference anything
1432 outside of the local scope (nor can any methods it calls).
1433
1434 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001435 if self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001436 if not self._waitpid_lock.acquire(False):
1437 # Something else is busy calling waitpid. Don't allow two
1438 # at once. We know nothing yet.
1439 return None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001440 try:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001441 if self.returncode is not None:
1442 return self.returncode # Another thread waited.
Brett Cannon84df1e62010-05-14 00:33:40 +00001443 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001444 if pid == self.pid:
1445 self._handle_exitstatus(sts)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001446 except OSError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001447 if _deadstate is not None:
1448 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001449 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001450 # This happens if SIGCLD is set to be ignored or
1451 # waiting for child processes has otherwise been
1452 # disabled for our process. This child is dead, we
1453 # can't get the status.
1454 # http://bugs.python.org/issue15756
1455 self.returncode = 0
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001456 finally:
1457 self._waitpid_lock.release()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458 return self.returncode
1459
1460
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001461 def _try_wait(self, wait_flags):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001462 """All callers to this function MUST hold self._waitpid_lock."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001463 try:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001464 (pid, sts) = os.waitpid(self.pid, wait_flags)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001465 except ChildProcessError:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001466 # This happens if SIGCLD is set to be ignored or waiting
1467 # for child processes has otherwise been disabled for our
1468 # process. This child is dead, we can't get the status.
1469 pid = self.pid
1470 sts = 0
1471 return (pid, sts)
1472
1473
Gregory P. Smith82604e02016-11-20 16:31:07 -08001474 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001475 """Wait for child process to terminate. Returns returncode
1476 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001477 if self.returncode is not None:
1478 return self.returncode
Reid Kleckner2b228f02011-03-16 16:57:54 -04001479
Gregory P. Smith82604e02016-11-20 16:31:07 -08001480 if timeout is not None:
1481 endtime = _time() + timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001482 # Enter a busy loop if we have a timeout. This busy loop was
1483 # cribbed from Lib/threading.py in Thread.wait() at r71065.
1484 delay = 0.0005 # 500 us -> initial delay of 1 ms
1485 while True:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001486 if self._waitpid_lock.acquire(False):
1487 try:
1488 if self.returncode is not None:
1489 break # Another thread waited.
1490 (pid, sts) = self._try_wait(os.WNOHANG)
1491 assert pid == self.pid or pid == 0
1492 if pid == self.pid:
1493 self._handle_exitstatus(sts)
1494 break
1495 finally:
1496 self._waitpid_lock.release()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001497 remaining = self._remaining_time(endtime)
1498 if remaining <= 0:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001499 raise TimeoutExpired(self.args, timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001500 delay = min(delay * 2, remaining, .05)
1501 time.sleep(delay)
Gregory P. Smithf328d792012-11-10 21:06:18 -08001502 else:
1503 while self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001504 with self._waitpid_lock:
1505 if self.returncode is not None:
1506 break # Another thread waited.
1507 (pid, sts) = self._try_wait(0)
1508 # Check the pid and loop as waitpid has been known to
1509 # return 0 even without WNOHANG in odd situations.
1510 # http://bugs.python.org/issue14396.
1511 if pid == self.pid:
1512 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001513 return self.returncode
1514
1515
Reid Kleckner2b228f02011-03-16 16:57:54 -04001516 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001517 if self.stdin and not self._communication_started:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001518 # Flush stdio buffer. This might block, if the user has
1519 # been writing to .stdin in an uncontrolled fashion.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001520 try:
1521 self.stdin.flush()
1522 except BrokenPipeError:
1523 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001524 if not input:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001525 try:
1526 self.stdin.close()
1527 except BrokenPipeError:
1528 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001529
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001530 stdout = None
1531 stderr = None
1532
1533 # Only create this mapping if we haven't already.
1534 if not self._communication_started:
1535 self._fileobj2output = {}
1536 if self.stdout:
1537 self._fileobj2output[self.stdout] = []
1538 if self.stderr:
1539 self._fileobj2output[self.stderr] = []
1540
1541 if self.stdout:
1542 stdout = self._fileobj2output[self.stdout]
1543 if self.stderr:
1544 stderr = self._fileobj2output[self.stderr]
1545
1546 self._save_input(input)
1547
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001548 if self._input:
1549 input_view = memoryview(self._input)
1550
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001551 with _PopenSelector() as selector:
1552 if self.stdin and input:
1553 selector.register(self.stdin, selectors.EVENT_WRITE)
1554 if self.stdout:
1555 selector.register(self.stdout, selectors.EVENT_READ)
1556 if self.stderr:
1557 selector.register(self.stderr, selectors.EVENT_READ)
1558
1559 while selector.get_map():
1560 timeout = self._remaining_time(endtime)
1561 if timeout is not None and timeout < 0:
1562 raise TimeoutExpired(self.args, orig_timeout)
1563
1564 ready = selector.select(timeout)
1565 self._check_timeout(endtime, orig_timeout)
1566
1567 # XXX Rewrite these to use non-blocking I/O on the file
1568 # objects; they are no longer using C stdio!
1569
1570 for key, events in ready:
1571 if key.fileobj is self.stdin:
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001572 chunk = input_view[self._input_offset :
1573 self._input_offset + _PIPE_BUF]
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001574 try:
1575 self._input_offset += os.write(key.fd, chunk)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001576 except BrokenPipeError:
1577 selector.unregister(key.fileobj)
1578 key.fileobj.close()
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001579 else:
1580 if self._input_offset >= len(self._input):
1581 selector.unregister(key.fileobj)
1582 key.fileobj.close()
1583 elif key.fileobj in (self.stdout, self.stderr):
Gregory P. Smith7b83b182013-12-08 10:58:28 -08001584 data = os.read(key.fd, 32768)
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001585 if not data:
1586 selector.unregister(key.fileobj)
1587 key.fileobj.close()
1588 self._fileobj2output[key.fileobj].append(data)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001589
1590 self.wait(timeout=self._remaining_time(endtime))
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001591
1592 # All data exchanged. Translate lists into strings.
1593 if stdout is not None:
1594 stdout = b''.join(stdout)
1595 if stderr is not None:
1596 stderr = b''.join(stderr)
1597
1598 # Translate newlines, if requested.
1599 # This also turns bytes into strings.
andyclegg7fed7bd2017-10-23 03:01:19 +01001600 if self.text_mode:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001601 if stdout is not None:
1602 stdout = self._translate_newlines(stdout,
Steve Dower050acae2016-09-06 20:16:17 -07001603 self.stdout.encoding,
1604 self.stdout.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001605 if stderr is not None:
1606 stderr = self._translate_newlines(stderr,
Steve Dower050acae2016-09-06 20:16:17 -07001607 self.stderr.encoding,
1608 self.stderr.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001609
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001610 return (stdout, stderr)
1611
1612
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001613 def _save_input(self, input):
1614 # This method is called from the _communicate_with_*() methods
1615 # so that if we time out while communicating, we can continue
1616 # sending input if we retry.
1617 if self.stdin and self._input is None:
1618 self._input_offset = 0
1619 self._input = input
andyclegg7fed7bd2017-10-23 03:01:19 +01001620 if input is not None and self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -07001621 self._input = self._input.encode(self.stdin.encoding,
1622 self.stdin.errors)
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001623
1624
Christian Heimesa342c012008-04-20 21:01:16 +00001625 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001626 """Send a signal to the process."""
1627 # Skip signalling a process that we know has already died.
1628 if self.returncode is None:
1629 os.kill(self.pid, sig)
Christian Heimesa342c012008-04-20 21:01:16 +00001630
1631 def terminate(self):
1632 """Terminate the process with SIGTERM
1633 """
1634 self.send_signal(signal.SIGTERM)
1635
1636 def kill(self):
1637 """Kill the process with SIGKILL
1638 """
1639 self.send_signal(signal.SIGKILL)