blob: 43be1f9bffa387be09d8ec977c7e61bad40ef155 [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
244 settings in sys.flags and sys.warnoptions."""
245 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)
263 for opt in sys.warnoptions:
264 args.append('-W' + opt)
265 return args
266
267
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400268def call(*popenargs, timeout=None, **kwargs):
269 """Run command with arguments. Wait for command to complete or
270 timeout, then return the returncode attribute.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 The arguments are the same as for the Popen constructor. Example:
273
274 retcode = call(["ls", "-l"])
275 """
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200276 with Popen(*popenargs, **kwargs) as p:
277 try:
278 return p.wait(timeout=timeout)
279 except:
280 p.kill()
281 p.wait()
282 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283
284
Peter Astrand454f7672005-01-01 09:36:35 +0000285def check_call(*popenargs, **kwargs):
286 """Run command with arguments. Wait for command to complete. If
287 the exit code was zero then return, otherwise raise
288 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000290
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400291 The arguments are the same as for the call function. Example:
Peter Astrand454f7672005-01-01 09:36:35 +0000292
293 check_call(["ls", "-l"])
294 """
295 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000296 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000297 cmd = kwargs.get("args")
298 if cmd is None:
299 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000300 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000301 return 0
302
303
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400304def check_output(*popenargs, timeout=None, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700305 r"""Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000306
307 If the exit code was non-zero it raises a CalledProcessError. The
308 CalledProcessError object will have the return code in the returncode
309 attribute and output in the output attribute.
310
311 The arguments are the same as for the Popen constructor. Example:
312
313 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000314 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000315
316 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000317 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000318
319 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000320 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000321 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000322 b'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith91110f52013-03-19 23:25:16 -0700323
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300324 There is an additional optional argument, "input", allowing you to
325 pass a string to the subprocess's stdin. If you use this argument
326 you may not also use the Popen constructor's "stdin" argument, as
327 it too will be used internally. Example:
328
329 >>> check_output(["sed", "-e", "s/foo/bar/"],
330 ... input=b"when in the course of fooman events\n")
331 b'when in the course of barman events\n'
332
andyclegg7fed7bd2017-10-23 03:01:19 +0100333 By default, all communication is in bytes, and therefore any "input"
334 should be bytes, and the return value wil be bytes. If in text mode,
335 any "input" should be a string, and the return value will be a string
336 decoded according to locale encoding, or by "encoding" if set. Text mode
337 is triggered by setting any of text, encoding, errors or universal_newlines.
Georg Brandlf9734072008-12-07 15:30:06 +0000338 """
339 if 'stdout' in kwargs:
340 raise ValueError('stdout argument not allowed, it will be overridden.')
Gregory P. Smith6e730002015-04-14 16:14:25 -0700341
342 if 'input' in kwargs and kwargs['input'] is None:
343 # Explicitly passing input=None was previously equivalent to passing an
344 # empty string. That is maintained here for backwards compatibility.
345 kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''
346
347 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
348 **kwargs).stdout
349
350
351class CompletedProcess(object):
352 """A process that has finished running.
353
354 This is returned by run().
355
356 Attributes:
357 args: The list or str args passed to run().
358 returncode: The exit code of the process, negative for signals.
359 stdout: The standard output (None if not captured).
360 stderr: The standard error (None if not captured).
361 """
362 def __init__(self, args, returncode, stdout=None, stderr=None):
363 self.args = args
364 self.returncode = returncode
365 self.stdout = stdout
366 self.stderr = stderr
367
368 def __repr__(self):
369 args = ['args={!r}'.format(self.args),
370 'returncode={!r}'.format(self.returncode)]
371 if self.stdout is not None:
372 args.append('stdout={!r}'.format(self.stdout))
373 if self.stderr is not None:
374 args.append('stderr={!r}'.format(self.stderr))
375 return "{}({})".format(type(self).__name__, ', '.join(args))
376
377 def check_returncode(self):
378 """Raise CalledProcessError if the exit code is non-zero."""
379 if self.returncode:
380 raise CalledProcessError(self.returncode, self.args, self.stdout,
381 self.stderr)
382
383
384def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
385 """Run command with arguments and return a CompletedProcess instance.
386
387 The returned instance will have attributes args, returncode, stdout and
388 stderr. By default, stdout and stderr are not captured, and those attributes
389 will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
390
391 If check is True and the exit code was non-zero, it raises a
392 CalledProcessError. The CalledProcessError object will have the return code
393 in the returncode attribute, and output & stderr attributes if those streams
394 were captured.
395
396 If timeout is given, and the process takes too long, a TimeoutExpired
397 exception will be raised.
398
399 There is an optional argument "input", allowing you to
andyclegg7fed7bd2017-10-23 03:01:19 +0100400 pass bytes or a string to the subprocess's stdin. If you use this argument
Gregory P. Smith6e730002015-04-14 16:14:25 -0700401 you may not also use the Popen constructor's "stdin" argument, as
402 it will be used internally.
403
andyclegg7fed7bd2017-10-23 03:01:19 +0100404 By default, all communication is in bytes, and therefore any "input" should
405 be bytes, and the stdout and stderr will be bytes. If in text mode, any
406 "input" should be a string, and stdout and stderr will be strings decoded
407 according to locale encoding, or by "encoding" if set. Text mode is
408 triggered by setting any of text, encoding, errors or universal_newlines.
Gregory P. Smith6e730002015-04-14 16:14:25 -0700409
andyclegg7fed7bd2017-10-23 03:01:19 +0100410 The other arguments are the same as for the Popen constructor.
Gregory P. Smith6e730002015-04-14 16:14:25 -0700411 """
412 if input is not None:
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300413 if 'stdin' in kwargs:
414 raise ValueError('stdin and input arguments may not both be used.')
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300415 kwargs['stdin'] = PIPE
Gregory P. Smith6e730002015-04-14 16:14:25 -0700416
417 with Popen(*popenargs, **kwargs) as process:
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200418 try:
Gregory P. Smith6e730002015-04-14 16:14:25 -0700419 stdout, stderr = process.communicate(input, timeout=timeout)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200420 except TimeoutExpired:
421 process.kill()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700422 stdout, stderr = process.communicate()
423 raise TimeoutExpired(process.args, timeout, output=stdout,
424 stderr=stderr)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200425 except:
426 process.kill()
427 process.wait()
428 raise
429 retcode = process.poll()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700430 if check and retcode:
431 raise CalledProcessError(retcode, process.args,
432 output=stdout, stderr=stderr)
433 return CompletedProcess(process.args, retcode, stdout, stderr)
Peter Astrand454f7672005-01-01 09:36:35 +0000434
435
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436def list2cmdline(seq):
437 """
438 Translate a sequence of arguments into a command line
439 string, using the same rules as the MS C runtime:
440
441 1) Arguments are delimited by white space, which is either a
442 space or a tab.
443
444 2) A string surrounded by double quotation marks is
445 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000446 contained within. A quoted string can be embedded in an
447 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448
449 3) A double quotation mark preceded by a backslash is
450 interpreted as a literal double quotation mark.
451
452 4) Backslashes are interpreted literally, unless they
453 immediately precede a double quotation mark.
454
455 5) If backslashes immediately precede a double quotation mark,
456 every pair of backslashes is interpreted as a literal
457 backslash. If the number of backslashes is odd, the last
458 backslash escapes the next double quotation mark as
459 described in rule 3.
460 """
461
462 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000463 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
464 # or search http://msdn.microsoft.com for
465 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 result = []
467 needquote = False
468 for arg in seq:
469 bs_buf = []
470
471 # Add a space to separate this argument from the others
472 if result:
473 result.append(' ')
474
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000475 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 if needquote:
477 result.append('"')
478
479 for c in arg:
480 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000481 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 bs_buf.append(c)
483 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000484 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 result.append('\\' * len(bs_buf)*2)
486 bs_buf = []
487 result.append('\\"')
488 else:
489 # Normal char
490 if bs_buf:
491 result.extend(bs_buf)
492 bs_buf = []
493 result.append(c)
494
Christian Heimesfdab48e2008-01-20 09:06:41 +0000495 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 if bs_buf:
497 result.extend(bs_buf)
498
499 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000500 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 result.append('"')
502
503 return ''.join(result)
504
505
Brett Cannona23810f2008-05-26 19:04:21 +0000506# Various tools for executing commands and looking at their output and status.
507#
Brett Cannona23810f2008-05-26 19:04:21 +0000508
509def getstatusoutput(cmd):
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700510 """Return (exitcode, output) of executing cmd in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000511
Tim Golden60798142013-11-05 12:57:25 +0000512 Execute the string 'cmd' in a shell with 'check_output' and
Steve Dower050acae2016-09-06 20:16:17 -0700513 return a 2-tuple (status, output). The locale encoding is used
514 to decode the output and process newlines.
Tim Golden60798142013-11-05 12:57:25 +0000515
516 A trailing newline is stripped from the output.
517 The exit status for the command can be interpreted
518 according to the rules for the function 'wait'. Example:
Brett Cannona23810f2008-05-26 19:04:21 +0000519
520 >>> import subprocess
521 >>> subprocess.getstatusoutput('ls /bin/ls')
522 (0, '/bin/ls')
523 >>> subprocess.getstatusoutput('cat /bin/junk')
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700524 (1, 'cat: /bin/junk: No such file or directory')
Brett Cannona23810f2008-05-26 19:04:21 +0000525 >>> subprocess.getstatusoutput('/bin/junk')
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700526 (127, 'sh: /bin/junk: not found')
527 >>> subprocess.getstatusoutput('/bin/kill $$')
528 (-15, '')
Brett Cannona23810f2008-05-26 19:04:21 +0000529 """
Tim Goldene0041752013-11-03 12:53:17 +0000530 try:
andyclegg7fed7bd2017-10-23 03:01:19 +0100531 data = check_output(cmd, shell=True, text=True, stderr=STDOUT)
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700532 exitcode = 0
Tim Goldene0041752013-11-03 12:53:17 +0000533 except CalledProcessError as ex:
534 data = ex.output
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700535 exitcode = ex.returncode
Tim Goldene0041752013-11-03 12:53:17 +0000536 if data[-1:] == '\n':
537 data = data[:-1]
Gregory P. Smith2eb0cb42017-09-07 16:11:02 -0700538 return exitcode, data
Brett Cannona23810f2008-05-26 19:04:21 +0000539
540def getoutput(cmd):
541 """Return output (stdout or stderr) of executing cmd in a shell.
542
543 Like getstatusoutput(), except the exit status is ignored and the return
544 value is a string containing the command's output. Example:
545
546 >>> import subprocess
547 >>> subprocess.getoutput('ls /bin/ls')
548 '/bin/ls'
549 """
550 return getstatusoutput(cmd)[1]
551
552
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000553_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000554
555
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556class Popen(object):
Martin Panter4afdca02016-10-25 22:20:48 +0000557 """ Execute a child program in a new process.
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200558
Martin Panter4afdca02016-10-25 22:20:48 +0000559 For a complete description of the arguments see the Python documentation.
560
561 Arguments:
562 args: A string, or a sequence of program arguments.
563
564 bufsize: supplied as the buffering argument to the open() function when
565 creating the stdin/stdout/stderr pipe file objects
566
567 executable: A replacement program to execute.
568
569 stdin, stdout and stderr: These specify the executed programs' standard
570 input, standard output and standard error file handles, respectively.
571
572 preexec_fn: (POSIX only) An object to be called in the child process
573 just before the child is executed.
574
575 close_fds: Controls closing or inheriting of file descriptors.
576
577 shell: If true, the command will be executed through the shell.
578
579 cwd: Sets the current directory before the child is executed.
580
581 env: Defines the environment variables for the new process.
582
andyclegg7fed7bd2017-10-23 03:01:19 +0100583 text: If true, decode stdin, stdout and stderr using the given encoding
584 (if set) or the system default otherwise.
585
586 universal_newlines: Alias of text, provided for backwards compatibility.
Martin Panter4afdca02016-10-25 22:20:48 +0000587
588 startupinfo and creationflags (Windows only)
589
590 restore_signals (POSIX only)
591
592 start_new_session (POSIX only)
593
594 pass_fds (POSIX only)
595
Martin Panter3dca6242016-10-25 23:41:42 +0000596 encoding and errors: Text mode encoding and error handling to use for
597 file objects stdin, stdout and stderr.
598
Martin Panter4afdca02016-10-25 22:20:48 +0000599 Attributes:
600 stdin, stdout, stderr, pid, returncode
601 """
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200602 _child_created = False # Set here since __del__ checks it
603
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700604 def __init__(self, args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000606 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
andyclegg7fed7bd2017-10-23 03:01:19 +0100607 shell=False, cwd=None, env=None, universal_newlines=None,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000608 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000609 restore_signals=True, start_new_session=False,
andyclegg7fed7bd2017-10-23 03:01:19 +0100610 pass_fds=(), *, encoding=None, errors=None, text=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 """Create new Popen instance."""
612 _cleanup()
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700613 # Held while anything is calling waitpid before returncode has been
614 # updated to prevent clobbering returncode if wait() or poll() are
615 # called from multiple threads at once. After acquiring the lock,
616 # code must re-check self.returncode to see if another thread just
617 # finished a waitpid() call.
618 self._waitpid_lock = threading.Lock()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400620 self._input = None
621 self._communication_started = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000622 if bufsize is None:
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700623 bufsize = -1 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000624 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000625 raise TypeError("bufsize must be an integer")
626
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700627 if _mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000628 if preexec_fn is not None:
629 raise ValueError("preexec_fn is not supported on Windows "
630 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000631 any_stdio_set = (stdin is not None or stdout is not None or
632 stderr is not None)
633 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
634 if any_stdio_set:
635 close_fds = False
636 else:
637 close_fds = True
638 elif close_fds and any_stdio_set:
639 raise ValueError(
640 "close_fds is not supported on Windows platforms"
641 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 else:
643 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000644 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
645 close_fds = True
646 if pass_fds and not close_fds:
647 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
648 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000649 if startupinfo is not None:
650 raise ValueError("startupinfo is only supported on Windows "
651 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000653 raise ValueError("creationflags is only supported on Windows "
654 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400656 self.args = args
Tim Peterse718f612004-10-12 21:51:32 +0000657 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 self.stdout = None
659 self.stderr = None
660 self.pid = None
661 self.returncode = None
Steve Dower050acae2016-09-06 20:16:17 -0700662 self.encoding = encoding
663 self.errors = errors
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664
andyclegg7fed7bd2017-10-23 03:01:19 +0100665 # Validate the combinations of text and universal_newlines
666 if (text is not None and universal_newlines is not None
667 and bool(universal_newlines) != bool(text)):
668 raise SubprocessError('Cannot disambiguate when both text '
669 'and universal_newlines are supplied but '
670 'different. Pass one or the other.')
671
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 # Input and output objects. The general principle is like
673 # this:
674 #
675 # Parent Child
676 # ------ -----
677 # p2cwrite ---stdin---> p2cread
678 # c2pread <--stdout--- c2pwrite
679 # errread <--stderr--- errwrite
680 #
681 # On POSIX, the child objects are file descriptors. On
682 # Windows, these are Windows file handles. The parent objects
683 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000684 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000686
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 (p2cread, p2cwrite,
688 c2pread, c2pwrite,
689 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
690
Antoine Pitrouc9982322011-01-04 19:07:07 +0000691 # We wrap OS handles *before* launching the child, otherwise a
692 # quickly terminating child could make our fds unwrappable
693 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700695 if _mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000696 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000697 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000698 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000699 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000700 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000701 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000702
andyclegg7fed7bd2017-10-23 03:01:19 +0100703 self.text_mode = encoding or errors or text or universal_newlines
Tim Peterse718f612004-10-12 21:51:32 +0000704
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700705 self._closed_child_pipe_fds = False
Steve Dower050acae2016-09-06 20:16:17 -0700706
Antoine Pitrouc9982322011-01-04 19:07:07 +0000707 try:
Steve Dower050acae2016-09-06 20:16:17 -0700708 if p2cwrite != -1:
709 self.stdin = io.open(p2cwrite, 'wb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100710 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700711 self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
712 line_buffering=(bufsize == 1),
713 encoding=encoding, errors=errors)
714 if c2pread != -1:
715 self.stdout = io.open(c2pread, 'rb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100716 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700717 self.stdout = io.TextIOWrapper(self.stdout,
718 encoding=encoding, errors=errors)
719 if errread != -1:
720 self.stderr = io.open(errread, 'rb', bufsize)
andyclegg7fed7bd2017-10-23 03:01:19 +0100721 if self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -0700722 self.stderr = io.TextIOWrapper(self.stderr,
723 encoding=encoding, errors=errors)
724
Antoine Pitrouc9982322011-01-04 19:07:07 +0000725 self._execute_child(args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300726 pass_fds, cwd, env,
Antoine Pitrouc9982322011-01-04 19:07:07 +0000727 startupinfo, creationflags, shell,
728 p2cread, p2cwrite,
729 c2pread, c2pwrite,
730 errread, errwrite,
731 restore_signals, start_new_session)
732 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800733 # Cleanup if the child failed starting.
734 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000735 try:
736 f.close()
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200737 except OSError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800738 pass # Ignore EBADF or other errors.
739
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700740 if not self._closed_child_pipe_fds:
741 to_close = []
742 if stdin == PIPE:
743 to_close.append(p2cread)
744 if stdout == PIPE:
745 to_close.append(c2pwrite)
746 if stderr == PIPE:
747 to_close.append(errwrite)
748 if hasattr(self, '_devnull'):
749 to_close.append(self._devnull)
750 for fd in to_close:
751 try:
Segev Finer4d385172017-08-18 16:18:13 +0300752 if _mswindows and isinstance(fd, Handle):
753 fd.Close()
754 else:
755 os.close(fd)
Gregory P. Smith22ba31a2013-06-15 18:14:56 -0700756 except OSError:
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700757 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800758
Antoine Pitrouc9982322011-01-04 19:07:07 +0000759 raise
760
andyclegg7fed7bd2017-10-23 03:01:19 +0100761 @property
762 def universal_newlines(self):
763 # universal_newlines as retained as an alias of text_mode for API
luzpaza5293b42017-11-05 07:37:50 -0600764 # compatibility. bpo-31756
andyclegg7fed7bd2017-10-23 03:01:19 +0100765 return self.text_mode
766
767 @universal_newlines.setter
768 def universal_newlines(self, universal_newlines):
769 self.text_mode = bool(universal_newlines)
770
Steve Dower050acae2016-09-06 20:16:17 -0700771 def _translate_newlines(self, data, encoding, errors):
772 data = data.decode(encoding, errors)
Andrew Svetlov82860712012-08-19 22:13:41 +0300773 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774
Brian Curtin79cdb662010-12-03 02:46:02 +0000775 def __enter__(self):
776 return self
777
778 def __exit__(self, type, value, traceback):
779 if self.stdout:
780 self.stdout.close()
781 if self.stderr:
782 self.stderr.close()
Serhiy Storchakaab900c22015-02-28 12:43:08 +0200783 try: # Flushing a BufferedWriter may raise an error
784 if self.stdin:
785 self.stdin.close()
786 finally:
787 # Wait for the process to terminate, to avoid zombies.
788 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000789
Victor Stinner9505b032017-01-06 10:44:44 +0100790 def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200791 if not self._child_created:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792 # We didn't get to successfully create a child process.
793 return
Victor Stinner5a48e212016-05-20 12:11:15 +0200794 if self.returncode is None:
Victor Stinnerc206f1e2016-06-14 16:42:59 +0200795 # Not reading subprocess exit status creates a zombi process which
796 # is only destroyed at the parent python process exit
Victor Stinner9505b032017-01-06 10:44:44 +0100797 _warn("subprocess %s is still running" % self.pid,
798 ResourceWarning, source=self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000800 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000801 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802 # Child is still running, keep us alive until we can wait on it.
803 _active.append(self)
804
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200805 def _get_devnull(self):
806 if not hasattr(self, '_devnull'):
807 self._devnull = os.open(os.devnull, os.O_RDWR)
808 return self._devnull
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809
Victor Stinnera5e881d2015-01-14 17:07:59 +0100810 def _stdin_write(self, input):
811 if input:
812 try:
813 self.stdin.write(input)
814 except BrokenPipeError:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000815 pass # communicate() must ignore broken pipe errors.
Victor Stinnerd52aa312017-06-08 17:30:39 +0200816 except OSError as exc:
817 if exc.errno == errno.EINVAL:
818 # bpo-19612, bpo-30418: On Windows, stdin.write() fails
819 # with EINVAL if the child process exited or if the child
820 # process is still running but closed the pipe.
Victor Stinnera5e881d2015-01-14 17:07:59 +0100821 pass
822 else:
823 raise
Victor Stinnerd52aa312017-06-08 17:30:39 +0200824
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000825 try:
826 self.stdin.close()
827 except BrokenPipeError:
828 pass # communicate() must ignore broken pipe errors.
Victor Stinnerd52aa312017-06-08 17:30:39 +0200829 except OSError as exc:
830 if exc.errno == errno.EINVAL:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +0000831 pass
832 else:
833 raise
Victor Stinnera5e881d2015-01-14 17:07:59 +0100834
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400835 def communicate(self, input=None, timeout=None):
Joel Schaerer88031a92017-09-13 21:11:20 +0200836 """Interact with process: Send data to stdin and close it.
837 Read data from stdout and stderr, until end-of-file is
838 reached. Wait for process to terminate.
Tim Peterseba28be2005-03-28 01:08:02 +0000839
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400840 The optional "input" argument should be data to be sent to the
andyclegg7fed7bd2017-10-23 03:01:19 +0100841 child process, or None, if no data should be sent to the child.
842 communicate() returns a tuple (stdout, stderr).
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400843
andyclegg7fed7bd2017-10-23 03:01:19 +0100844 By default, all communication is in bytes, and therefore any
845 "input" should be bytes, and the (stdout, stderr) will be bytes.
846 If in text mode (indicated by self.text_mode), any "input" should
847 be a string, and (stdout, stderr) will be strings decoded
848 according to locale encoding, or by "encoding" if set. Text mode
849 is triggered by setting any of text, encoding, errors or
850 universal_newlines.
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400851 """
Peter Astrand23109f02005-03-03 20:28:59 +0000852
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400853 if self._communication_started and input:
854 raise ValueError("Cannot send input after starting communication")
855
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400856 # Optimization: If we are not worried about timeouts, we haven't
857 # started communicating, and we have one or zero pipes, using select()
858 # or threads is unnecessary.
Victor Stinner7a8d0812011-04-05 13:13:08 +0200859 if (timeout is None and not self._communication_started and
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400860 [self.stdin, self.stdout, self.stderr].count(None) >= 2):
Tim Peterseba28be2005-03-28 01:08:02 +0000861 stdout = None
862 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000863 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +0100864 self._stdin_write(input)
Peter Astrand23109f02005-03-03 20:28:59 +0000865 elif self.stdout:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000866 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000867 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000868 elif self.stderr:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +0000869 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000870 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000871 self.wait()
Victor Stinner7a8d0812011-04-05 13:13:08 +0200872 else:
873 if timeout is not None:
Victor Stinner949d8c92012-05-30 13:30:32 +0200874 endtime = _time() + timeout
Victor Stinner7a8d0812011-04-05 13:13:08 +0200875 else:
876 endtime = None
Tim Peterseba28be2005-03-28 01:08:02 +0000877
Victor Stinner7a8d0812011-04-05 13:13:08 +0200878 try:
879 stdout, stderr = self._communicate(input, endtime, timeout)
880 finally:
881 self._communication_started = True
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400882
Victor Stinner7a8d0812011-04-05 13:13:08 +0200883 sts = self.wait(timeout=self._remaining_time(endtime))
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400884
885 return (stdout, stderr)
Peter Astrand23109f02005-03-03 20:28:59 +0000886
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000888 def poll(self):
Martin Panter4afdca02016-10-25 22:20:48 +0000889 """Check if child process has terminated. Set and return returncode
890 attribute."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000891 return self._internal_poll()
892
893
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400894 def _remaining_time(self, endtime):
895 """Convenience for _communicate when computing timeouts."""
896 if endtime is None:
897 return None
898 else:
Victor Stinner949d8c92012-05-30 13:30:32 +0200899 return endtime - _time()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400900
901
Reid Kleckner2b228f02011-03-16 16:57:54 -0400902 def _check_timeout(self, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400903 """Convenience for checking if a timeout has expired."""
904 if endtime is None:
905 return
Victor Stinner949d8c92012-05-30 13:30:32 +0200906 if _time() > endtime:
Reid Kleckner2b228f02011-03-16 16:57:54 -0400907 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400908
909
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700910 if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 #
912 # Windows methods
913 #
914 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000915 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000916 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
917 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000918 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000919 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000920
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000921 p2cread, p2cwrite = -1, -1
922 c2pread, c2pwrite = -1, -1
923 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924
Peter Astrandd38ddf42005-02-10 08:32:50 +0000925 if stdin is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200926 p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000927 if p2cread is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200928 p2cread, _ = _winapi.CreatePipe(None, 0)
929 p2cread = Handle(p2cread)
930 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000931 elif stdin == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200932 p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
933 p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200934 elif stdin == DEVNULL:
935 p2cread = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000936 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937 p2cread = msvcrt.get_osfhandle(stdin)
938 else:
939 # Assuming file-like object
940 p2cread = msvcrt.get_osfhandle(stdin.fileno())
941 p2cread = self._make_inheritable(p2cread)
942
Peter Astrandd38ddf42005-02-10 08:32:50 +0000943 if stdout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200944 c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000945 if c2pwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200946 _, c2pwrite = _winapi.CreatePipe(None, 0)
947 c2pwrite = Handle(c2pwrite)
948 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000949 elif stdout == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200950 c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
951 c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200952 elif stdout == DEVNULL:
953 c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000954 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955 c2pwrite = msvcrt.get_osfhandle(stdout)
956 else:
957 # Assuming file-like object
958 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
959 c2pwrite = self._make_inheritable(c2pwrite)
960
Peter Astrandd38ddf42005-02-10 08:32:50 +0000961 if stderr is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200962 errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000963 if errwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200964 _, errwrite = _winapi.CreatePipe(None, 0)
965 errwrite = Handle(errwrite)
966 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000967 elif stderr == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200968 errread, errwrite = _winapi.CreatePipe(None, 0)
969 errread, errwrite = Handle(errread), Handle(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970 elif stderr == STDOUT:
971 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200972 elif stderr == DEVNULL:
973 errwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000974 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 errwrite = msvcrt.get_osfhandle(stderr)
976 else:
977 # Assuming file-like object
978 errwrite = msvcrt.get_osfhandle(stderr.fileno())
979 errwrite = self._make_inheritable(errwrite)
980
981 return (p2cread, p2cwrite,
982 c2pread, c2pwrite,
983 errread, errwrite)
984
985
986 def _make_inheritable(self, handle):
987 """Return a duplicate of handle, which is inheritable"""
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200988 h = _winapi.DuplicateHandle(
989 _winapi.GetCurrentProcess(), handle,
990 _winapi.GetCurrentProcess(), 0, 1,
991 _winapi.DUPLICATE_SAME_ACCESS)
992 return Handle(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000993
994
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300996 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 startupinfo, creationflags, shell,
998 p2cread, p2cwrite,
999 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001000 errread, errwrite,
1001 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 """Execute program (MS Windows version)"""
1003
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001004 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001005
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001006 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 args = list2cmdline(args)
1008
Peter Astrandc1d65362004-11-07 14:30:34 +00001009 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +00001010 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001011 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +00001012 if -1 not in (p2cread, c2pwrite, errwrite):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001013 startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +00001014 startupinfo.hStdInput = p2cread
1015 startupinfo.hStdOutput = c2pwrite
1016 startupinfo.hStdError = errwrite
1017
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 if shell:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001019 startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
1020 startupinfo.wShowWindow = _winapi.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001021 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +00001022 args = '{} /c "{}"'.format (comspec, args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001023
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024 # Start the process
1025 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001026 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +00001027 # no special security
1028 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001029 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +00001030 creationflags,
1031 env,
Benjamin Petersoncb90f262017-03-02 00:03:41 -08001032 os.fspath(cwd) if cwd is not None else None,
Tim Peterse8374a52004-10-13 03:15:00 +00001033 startupinfo)
Tim Goldenad537f22010-08-08 11:18:16 +00001034 finally:
1035 # Child is launched. Close the parent's copy of those pipe
1036 # handles that only the child should have open. You need
1037 # to make sure that no handles to the write end of the
1038 # output pipe are maintained in this process or else the
1039 # pipe will not close when the child process exits and the
1040 # ReadFile will hang.
1041 if p2cread != -1:
1042 p2cread.Close()
1043 if c2pwrite != -1:
1044 c2pwrite.Close()
1045 if errwrite != -1:
1046 errwrite.Close()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001047 if hasattr(self, '_devnull'):
1048 os.close(self._devnull)
Segev Finer4d385172017-08-18 16:18:13 +03001049 # Prevent a double close of these handles/fds from __init__
1050 # on error.
1051 self._closed_child_pipe_fds = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001052
1053 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001054 self._child_created = True
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001055 self._handle = Handle(hp)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001056 self.pid = pid
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001057 _winapi.CloseHandle(ht)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058
Brett Cannon84df1e62010-05-14 00:33:40 +00001059 def _internal_poll(self, _deadstate=None,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001060 _WaitForSingleObject=_winapi.WaitForSingleObject,
1061 _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
1062 _GetExitCodeProcess=_winapi.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001064 attribute.
1065
1066 This method is called by __del__, so it can only refer to objects
1067 in its local scope.
1068
1069 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001070 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001071 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1072 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 return self.returncode
1074
1075
Gregory P. Smith82604e02016-11-20 16:31:07 -08001076 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001077 """Wait for child process to terminate. Returns returncode
1078 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001079 if timeout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001080 timeout_millis = _winapi.INFINITE
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001081 else:
Reid Kleckner91156ff2011-03-21 10:06:10 -07001082 timeout_millis = int(timeout * 1000)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001083 if self.returncode is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001084 result = _winapi.WaitForSingleObject(self._handle,
1085 timeout_millis)
1086 if result == _winapi.WAIT_TIMEOUT:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001087 raise TimeoutExpired(self.args, timeout)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001088 self.returncode = _winapi.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 return self.returncode
1090
1091
1092 def _readerthread(self, fh, buffer):
1093 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001094 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001095
1096
Reid Kleckner2b228f02011-03-16 16:57:54 -04001097 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001098 # Start reader threads feeding into a list hanging off of this
1099 # object, unless they've already been started.
1100 if self.stdout and not hasattr(self, "_stdout_buff"):
1101 self._stdout_buff = []
1102 self.stdout_thread = \
1103 threading.Thread(target=self._readerthread,
1104 args=(self.stdout, self._stdout_buff))
1105 self.stdout_thread.daemon = True
1106 self.stdout_thread.start()
1107 if self.stderr and not hasattr(self, "_stderr_buff"):
1108 self._stderr_buff = []
1109 self.stderr_thread = \
1110 threading.Thread(target=self._readerthread,
1111 args=(self.stderr, self._stderr_buff))
1112 self.stderr_thread.daemon = True
1113 self.stderr_thread.start()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114
1115 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +01001116 self._stdin_write(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001118 # Wait for the reader threads, or time out. If we time out, the
1119 # threads remain reading and the fds left open in case the user
1120 # calls communicate again.
1121 if self.stdout is not None:
1122 self.stdout_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001123 if self.stdout_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001124 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001125 if self.stderr is not None:
1126 self.stderr_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001127 if self.stderr_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001128 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001129
1130 # Collect the output from and close both pipes, now that we know
1131 # both have been read successfully.
1132 stdout = None
1133 stderr = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001135 stdout = self._stdout_buff
1136 self.stdout.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001137 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001138 stderr = self._stderr_buff
1139 self.stderr.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140
1141 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001142 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001143 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001144 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001145 stderr = stderr[0]
1146
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001147 return (stdout, stderr)
1148
Christian Heimesa342c012008-04-20 21:01:16 +00001149 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001150 """Send a signal to the process."""
1151 # Don't signal a process that we know has already died.
1152 if self.returncode is not None:
1153 return
Christian Heimesa342c012008-04-20 21:01:16 +00001154 if sig == signal.SIGTERM:
1155 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001156 elif sig == signal.CTRL_C_EVENT:
1157 os.kill(self.pid, signal.CTRL_C_EVENT)
1158 elif sig == signal.CTRL_BREAK_EVENT:
1159 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001160 else:
Brian Curtin19651362010-09-07 13:24:38 +00001161 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001162
1163 def terminate(self):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001164 """Terminates the process."""
1165 # Don't terminate a process that we know has already died.
1166 if self.returncode is not None:
1167 return
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001168 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001169 _winapi.TerminateProcess(self._handle, 1)
Antoine Pitroub69ef162012-03-11 19:33:29 +01001170 except PermissionError:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001171 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1172 # process already died.
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001173 rc = _winapi.GetExitCodeProcess(self._handle)
1174 if rc == _winapi.STILL_ACTIVE:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001175 raise
1176 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001177
1178 kill = terminate
1179
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001180 else:
1181 #
1182 # POSIX methods
1183 #
1184 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001185 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001186 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1187 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001188 p2cread, p2cwrite = -1, -1
1189 c2pread, c2pwrite = -1, -1
1190 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001191
Peter Astrandd38ddf42005-02-10 08:32:50 +00001192 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193 pass
1194 elif stdin == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001195 p2cread, p2cwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001196 elif stdin == DEVNULL:
1197 p2cread = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001198 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001199 p2cread = stdin
1200 else:
1201 # Assuming file-like object
1202 p2cread = stdin.fileno()
1203
Peter Astrandd38ddf42005-02-10 08:32:50 +00001204 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001205 pass
1206 elif stdout == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001207 c2pread, c2pwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001208 elif stdout == DEVNULL:
1209 c2pwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001210 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001211 c2pwrite = stdout
1212 else:
1213 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001214 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001215
Peter Astrandd38ddf42005-02-10 08:32:50 +00001216 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001217 pass
1218 elif stderr == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001219 errread, errwrite = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001220 elif stderr == STDOUT:
Martin Panterc7635892016-05-13 01:54:44 +00001221 if c2pwrite != -1:
1222 errwrite = c2pwrite
1223 else: # child's stdout is not set, use parent's stdout
1224 errwrite = sys.__stdout__.fileno()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001225 elif stderr == DEVNULL:
1226 errwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001227 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001228 errwrite = stderr
1229 else:
1230 # Assuming file-like object
1231 errwrite = stderr.fileno()
1232
1233 return (p2cread, p2cwrite,
1234 c2pread, c2pwrite,
1235 errread, errwrite)
1236
1237
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001238 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001239 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001240 startupinfo, creationflags, shell,
1241 p2cread, p2cwrite,
1242 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001243 errread, errwrite,
1244 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245 """Execute program (POSIX version)"""
1246
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001247 if isinstance(args, (str, bytes)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001248 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001249 else:
1250 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001251
1252 if shell:
Xavier de Gayeb35fc622016-12-13 16:32:21 +01001253 # On Android the default shell is at '/system/bin/sh'.
1254 unix_shell = ('/system/bin/sh' if
1255 hasattr(sys, 'getandroidapilevel') else '/bin/sh')
1256 args = [unix_shell, "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001257 if executable:
1258 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001259
Peter Astrandd38ddf42005-02-10 08:32:50 +00001260 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001261 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001262 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001263
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001264 # For transferring possible exec failure from child to parent.
1265 # Data format: "exception name:hex errno:description"
1266 # Pickle is not used; it is complex and involves memory allocation.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001267 errpipe_read, errpipe_write = os.pipe()
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001268 # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
1269 low_fds_to_close = []
1270 while errpipe_write < 3:
1271 low_fds_to_close.append(errpipe_write)
1272 errpipe_write = os.dup(errpipe_write)
1273 for low_fd in low_fds_to_close:
1274 os.close(low_fd)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001275 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001276 try:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001277 # We must avoid complex work that could involve
1278 # malloc or free in the child process to avoid
1279 # potential deadlocks, thus we do all this here.
1280 # and pass it to fork_exec()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001281
Victor Stinner372b8382011-06-21 17:24:21 +02001282 if env is not None:
Serhiy Storchakad174d242017-06-23 19:39:27 +03001283 env_list = []
1284 for k, v in env.items():
1285 k = os.fsencode(k)
1286 if b'=' in k:
1287 raise ValueError("illegal environment variable name")
1288 env_list.append(k + b'=' + os.fsencode(v))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001289 else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001290 env_list = None # Use execv instead of execve.
1291 executable = os.fsencode(executable)
1292 if os.path.dirname(executable):
1293 executable_list = (executable,)
1294 else:
1295 # This matches the behavior of os._execvpe().
1296 executable_list = tuple(
1297 os.path.join(os.fsencode(dir), executable)
1298 for dir in os.get_exec_path(env))
Gregory P. Smith361e30c2013-12-01 00:12:24 -08001299 fds_to_keep = set(pass_fds)
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001300 fds_to_keep.add(errpipe_write)
1301 self.pid = _posixsubprocess.fork_exec(
1302 args, executable_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03001303 close_fds, tuple(sorted(map(int, fds_to_keep))),
1304 cwd, env_list,
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001305 p2cread, p2cwrite, c2pread, c2pwrite,
1306 errread, errwrite,
1307 errpipe_read, errpipe_write,
1308 restore_signals, start_new_session, preexec_fn)
Charles-François Natali558639f2011-08-18 19:11:29 +02001309 self._child_created = True
Facundo Batista10706e22009-06-19 20:34:30 +00001310 finally:
1311 # be sure the FD is closed no matter what
1312 os.close(errpipe_write)
1313
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001314 # self._devnull is not always defined.
1315 devnull_fd = getattr(self, '_devnull', None)
1316 if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001317 os.close(p2cread)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001318 if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001319 os.close(c2pwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001320 if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001321 os.close(errwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001322 if devnull_fd is not None:
1323 os.close(devnull_fd)
1324 # Prevent a double close of these fds from __init__ on error.
1325 self._closed_child_pipe_fds = True
Facundo Batista10706e22009-06-19 20:34:30 +00001326
1327 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001328 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001329 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001330 while True:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001331 part = os.read(errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001332 errpipe_data += part
1333 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001334 break
Facundo Batista10706e22009-06-19 20:34:30 +00001335 finally:
1336 # be sure the FD is closed no matter what
1337 os.close(errpipe_read)
1338
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001339 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001340 try:
Victor Stinnera58e2c52016-05-20 12:08:12 +02001341 pid, sts = os.waitpid(self.pid, 0)
1342 if pid == self.pid:
1343 self._handle_exitstatus(sts)
1344 else:
1345 self.returncode = sys.maxsize
Victor Stinnera5e881d2015-01-14 17:07:59 +01001346 except ChildProcessError:
1347 pass
Victor Stinnera58e2c52016-05-20 12:08:12 +02001348
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001349 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001350 exception_name, hex_errno, err_msg = (
1351 errpipe_data.split(b':', 2))
Ammar Askar3fc499b2017-09-06 02:41:30 -04001352 # The encoding here should match the encoding
1353 # written in by the subprocess implementations
1354 # like _posixsubprocess
1355 err_msg = err_msg.decode()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001356 except ValueError:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001357 exception_name = b'SubprocessError'
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001358 hex_errno = b'0'
Ammar Askar3fc499b2017-09-06 02:41:30 -04001359 err_msg = 'Bad exception data from child: {!r}'.format(
1360 bytes(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001361 child_exception_type = getattr(
1362 builtins, exception_name.decode('ascii'),
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001363 SubprocessError)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001364 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001365 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001366 child_exec_never_called = (err_msg == "noexec")
1367 if child_exec_never_called:
1368 err_msg = ""
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001369 # The error must be from chdir(cwd).
1370 err_filename = cwd
1371 else:
1372 err_filename = orig_executable
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001373 if errno_num != 0:
1374 err_msg = os.strerror(errno_num)
1375 if errno_num == errno.ENOENT:
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001376 err_msg += ': ' + repr(err_filename)
1377 raise child_exception_type(errno_num, err_msg, err_filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001378 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001379
1380
Brett Cannon84df1e62010-05-14 00:33:40 +00001381 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1382 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
Gregory P. Smith50e16e32017-01-22 17:28:38 -08001383 _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED,
1384 _WSTOPSIG=os.WSTOPSIG):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001385 """All callers to this function MUST hold self._waitpid_lock."""
Brett Cannon84df1e62010-05-14 00:33:40 +00001386 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka72e77612014-02-10 19:20:22 +02001387 # refer to anything outside of its local scope.
Brett Cannon84df1e62010-05-14 00:33:40 +00001388 if _WIFSIGNALED(sts):
1389 self.returncode = -_WTERMSIG(sts)
1390 elif _WIFEXITED(sts):
1391 self.returncode = _WEXITSTATUS(sts)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08001392 elif _WIFSTOPPED(sts):
1393 self.returncode = -_WSTOPSIG(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001394 else:
1395 # Should never happen
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001396 raise SubprocessError("Unknown child exit status!")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001397
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001398
Brett Cannon84df1e62010-05-14 00:33:40 +00001399 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov1d960fe2012-12-24 20:08:53 +02001400 _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001401 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001402 attribute.
1403
1404 This method is called by __del__, so it cannot reference anything
1405 outside of the local scope (nor can any methods it calls).
1406
1407 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001408 if self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001409 if not self._waitpid_lock.acquire(False):
1410 # Something else is busy calling waitpid. Don't allow two
1411 # at once. We know nothing yet.
1412 return None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001413 try:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001414 if self.returncode is not None:
1415 return self.returncode # Another thread waited.
Brett Cannon84df1e62010-05-14 00:33:40 +00001416 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001417 if pid == self.pid:
1418 self._handle_exitstatus(sts)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001419 except OSError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001420 if _deadstate is not None:
1421 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001422 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001423 # This happens if SIGCLD is set to be ignored or
1424 # waiting for child processes has otherwise been
1425 # disabled for our process. This child is dead, we
1426 # can't get the status.
1427 # http://bugs.python.org/issue15756
1428 self.returncode = 0
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001429 finally:
1430 self._waitpid_lock.release()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001431 return self.returncode
1432
1433
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001434 def _try_wait(self, wait_flags):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001435 """All callers to this function MUST hold self._waitpid_lock."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001436 try:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001437 (pid, sts) = os.waitpid(self.pid, wait_flags)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001438 except ChildProcessError:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001439 # This happens if SIGCLD is set to be ignored or waiting
1440 # for child processes has otherwise been disabled for our
1441 # process. This child is dead, we can't get the status.
1442 pid = self.pid
1443 sts = 0
1444 return (pid, sts)
1445
1446
Gregory P. Smith82604e02016-11-20 16:31:07 -08001447 def wait(self, timeout=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001448 """Wait for child process to terminate. Returns returncode
1449 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001450 if self.returncode is not None:
1451 return self.returncode
Reid Kleckner2b228f02011-03-16 16:57:54 -04001452
Gregory P. Smith82604e02016-11-20 16:31:07 -08001453 if timeout is not None:
1454 endtime = _time() + timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001455 # Enter a busy loop if we have a timeout. This busy loop was
1456 # cribbed from Lib/threading.py in Thread.wait() at r71065.
1457 delay = 0.0005 # 500 us -> initial delay of 1 ms
1458 while True:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001459 if self._waitpid_lock.acquire(False):
1460 try:
1461 if self.returncode is not None:
1462 break # Another thread waited.
1463 (pid, sts) = self._try_wait(os.WNOHANG)
1464 assert pid == self.pid or pid == 0
1465 if pid == self.pid:
1466 self._handle_exitstatus(sts)
1467 break
1468 finally:
1469 self._waitpid_lock.release()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001470 remaining = self._remaining_time(endtime)
1471 if remaining <= 0:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001472 raise TimeoutExpired(self.args, timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001473 delay = min(delay * 2, remaining, .05)
1474 time.sleep(delay)
Gregory P. Smithf328d792012-11-10 21:06:18 -08001475 else:
1476 while self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001477 with self._waitpid_lock:
1478 if self.returncode is not None:
1479 break # Another thread waited.
1480 (pid, sts) = self._try_wait(0)
1481 # Check the pid and loop as waitpid has been known to
1482 # return 0 even without WNOHANG in odd situations.
1483 # http://bugs.python.org/issue14396.
1484 if pid == self.pid:
1485 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001486 return self.returncode
1487
1488
Reid Kleckner2b228f02011-03-16 16:57:54 -04001489 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001490 if self.stdin and not self._communication_started:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001491 # Flush stdio buffer. This might block, if the user has
1492 # been writing to .stdin in an uncontrolled fashion.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001493 try:
1494 self.stdin.flush()
1495 except BrokenPipeError:
1496 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001497 if not input:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001498 try:
1499 self.stdin.close()
1500 except BrokenPipeError:
1501 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001502
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001503 stdout = None
1504 stderr = None
1505
1506 # Only create this mapping if we haven't already.
1507 if not self._communication_started:
1508 self._fileobj2output = {}
1509 if self.stdout:
1510 self._fileobj2output[self.stdout] = []
1511 if self.stderr:
1512 self._fileobj2output[self.stderr] = []
1513
1514 if self.stdout:
1515 stdout = self._fileobj2output[self.stdout]
1516 if self.stderr:
1517 stderr = self._fileobj2output[self.stderr]
1518
1519 self._save_input(input)
1520
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001521 if self._input:
1522 input_view = memoryview(self._input)
1523
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001524 with _PopenSelector() as selector:
1525 if self.stdin and input:
1526 selector.register(self.stdin, selectors.EVENT_WRITE)
1527 if self.stdout:
1528 selector.register(self.stdout, selectors.EVENT_READ)
1529 if self.stderr:
1530 selector.register(self.stderr, selectors.EVENT_READ)
1531
1532 while selector.get_map():
1533 timeout = self._remaining_time(endtime)
1534 if timeout is not None and timeout < 0:
1535 raise TimeoutExpired(self.args, orig_timeout)
1536
1537 ready = selector.select(timeout)
1538 self._check_timeout(endtime, orig_timeout)
1539
1540 # XXX Rewrite these to use non-blocking I/O on the file
1541 # objects; they are no longer using C stdio!
1542
1543 for key, events in ready:
1544 if key.fileobj is self.stdin:
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001545 chunk = input_view[self._input_offset :
1546 self._input_offset + _PIPE_BUF]
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001547 try:
1548 self._input_offset += os.write(key.fd, chunk)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001549 except BrokenPipeError:
1550 selector.unregister(key.fileobj)
1551 key.fileobj.close()
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001552 else:
1553 if self._input_offset >= len(self._input):
1554 selector.unregister(key.fileobj)
1555 key.fileobj.close()
1556 elif key.fileobj in (self.stdout, self.stderr):
Gregory P. Smith7b83b182013-12-08 10:58:28 -08001557 data = os.read(key.fd, 32768)
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001558 if not data:
1559 selector.unregister(key.fileobj)
1560 key.fileobj.close()
1561 self._fileobj2output[key.fileobj].append(data)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001562
1563 self.wait(timeout=self._remaining_time(endtime))
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001564
1565 # All data exchanged. Translate lists into strings.
1566 if stdout is not None:
1567 stdout = b''.join(stdout)
1568 if stderr is not None:
1569 stderr = b''.join(stderr)
1570
1571 # Translate newlines, if requested.
1572 # This also turns bytes into strings.
andyclegg7fed7bd2017-10-23 03:01:19 +01001573 if self.text_mode:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001574 if stdout is not None:
1575 stdout = self._translate_newlines(stdout,
Steve Dower050acae2016-09-06 20:16:17 -07001576 self.stdout.encoding,
1577 self.stdout.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001578 if stderr is not None:
1579 stderr = self._translate_newlines(stderr,
Steve Dower050acae2016-09-06 20:16:17 -07001580 self.stderr.encoding,
1581 self.stderr.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001582
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001583 return (stdout, stderr)
1584
1585
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001586 def _save_input(self, input):
1587 # This method is called from the _communicate_with_*() methods
1588 # so that if we time out while communicating, we can continue
1589 # sending input if we retry.
1590 if self.stdin and self._input is None:
1591 self._input_offset = 0
1592 self._input = input
andyclegg7fed7bd2017-10-23 03:01:19 +01001593 if input is not None and self.text_mode:
Steve Dower050acae2016-09-06 20:16:17 -07001594 self._input = self._input.encode(self.stdin.encoding,
1595 self.stdin.errors)
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001596
1597
Christian Heimesa342c012008-04-20 21:01:16 +00001598 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001599 """Send a signal to the process."""
1600 # Skip signalling a process that we know has already died.
1601 if self.returncode is None:
1602 os.kill(self.pid, sig)
Christian Heimesa342c012008-04-20 21:01:16 +00001603
1604 def terminate(self):
1605 """Terminate the process with SIGTERM
1606 """
1607 self.send_signal(signal.SIGTERM)
1608
1609 def kill(self):
1610 """Kill the process with SIGKILL
1611 """
1612 self.send_signal(signal.SIGKILL)