blob: 9df93182451cd226fdbebfb347405ed064bbd42a [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
Raymond Hettinger837dd932004-10-17 16:36:53 +000010r"""subprocess - 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
13input/output/error pipes, and obtain their return codes. This module
Benjamin Peterson5eea8a72014-03-12 21:41:35 -050014intends to replace several older modules and functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000015
16os.system
17os.spawn*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018
19Information about how the subprocess module can be used to replace these
20modules and functions can be found below.
21
22
23
24Using the subprocess module
25===========================
26This module defines one class called Popen:
27
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070028class Popen(args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +000030 preexec_fn=None, close_fds=True, shell=False,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000031 cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000032 startupinfo=None, creationflags=0,
Steve Dower050acae2016-09-06 20:16:17 -070033 restore_signals=True, start_new_session=False, pass_fds=(),
34 *, encoding=None, errors=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035
36
37Arguments are:
38
39args should be a string, or a sequence of program arguments. The
40program to execute is normally the first item in the args sequence or
41string, but can be explicitly set by using the executable argument.
42
Gregory P. Smithf5604852010-12-13 06:45:02 +000043On POSIX, with shell=False (default): In this case, the Popen class
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000044uses os.execvp() to execute the child program. args should normally
45be a sequence. A string will be treated as a sequence with the string
46as the only item (the program to execute).
47
Gregory P. Smithf5604852010-12-13 06:45:02 +000048On POSIX, with shell=True: If args is a string, it specifies the
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000049command string to execute through the shell. If args is a sequence,
50the first item specifies the command string, and any additional items
51will be treated as additional shell arguments.
52
53On Windows: the Popen class uses CreateProcess() to execute the child
54program, which operates on strings. If args is a sequence, it will be
55converted to a string using the list2cmdline method. Please note that
56not all MS Windows applications interpret the command line the same
57way: The list2cmdline is designed for applications using the same
58rules as the MS C runtime.
59
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070060bufsize will be supplied as the corresponding argument to the io.open()
61function when creating the stdin/stdout/stderr pipe file objects:
620 means unbuffered (read & write are one system call and can return short),
631 means line buffered, any other positive value means use a buffer of
64approximately that size. A negative bufsize, the default, means the system
65default of io.DEFAULT_BUFFER_SIZE will be used.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000066
67stdin, stdout and stderr specify the executed programs' standard
68input, standard output and standard error file handles, respectively.
69Valid values are PIPE, an existing file descriptor (a positive
70integer), an existing file object, and None. PIPE indicates that a
71new pipe to the child should be created. With None, no redirection
72will occur; the child's file handles will be inherited from the
73parent. Additionally, stderr can be STDOUT, which indicates that the
74stderr data from the applications should be captured into the same
75file handle as for stdout.
76
Gregory P. Smithf5604852010-12-13 06:45:02 +000077On POSIX, if preexec_fn is set to a callable object, this object will be
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000078called in the child process just before the child is executed. The use
79of preexec_fn is not thread safe, using it in the presence of threads
80could lead to a deadlock in the child process before the new executable
81is executed.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000082
83If close_fds is true, all file descriptors except 0, 1 and 2 will be
Gregory P. Smithf5604852010-12-13 06:45:02 +000084closed before the child process is executed. The default for close_fds
Gregory P. Smith8edd99d2010-12-14 13:43:30 +000085varies by platform: Always true on POSIX. True when stdin/stdout/stderr
86are None on Windows, false otherwise.
87
88pass_fds is an optional sequence of file descriptors to keep open between the
89parent and child. Providing any pass_fds implicitly sets close_fds to true.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000090
91if shell is true, the specified command will be executed through the
92shell.
93
94If cwd is not None, the current directory will be changed to cwd
95before the child is executed.
96
Gregory P. Smithf5604852010-12-13 06:45:02 +000097On POSIX, if restore_signals is True all signals that Python sets to
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000098SIG_IGN are restored to SIG_DFL in the child process before the exec.
99Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This
100parameter does nothing on Windows.
101
Gregory P. Smithf5604852010-12-13 06:45:02 +0000102On POSIX, if start_new_session is True, the setsid() system call will be made
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000103in the child process prior to executing the command.
104
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105If env is not None, it defines the environment variables for the new
106process.
107
Steve Dower050acae2016-09-06 20:16:17 -0700108If encoding or errors are specified or universal_newlines is True, the file
109objects stdout and stderr are opened in text mode. See io.TextIOWrapper for
110the interpretation of these parameters are used.
Ronald Oussoren385521c2013-07-07 09:26:45 +0200111
Steve Dower050acae2016-09-06 20:16:17 -0700112If no encoding is specified and universal_newlines is False, the file
113objects stdin, stdout and stderr are opened as binary files, and no
114line ending conversion is done.
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400115
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116The startupinfo and creationflags, if given, will be passed to the
117underlying CreateProcess() function. They can specify things such as
118appearance of the main window and priority for the new process.
119(Windows only)
120
121
Georg Brandlf9734072008-12-07 15:30:06 +0000122This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123
Peter Astrand5f5e1412004-12-05 20:15:36 +0000124call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 Run command with arguments. Wait for command to complete, then
126 return the returncode attribute.
127
128 The arguments are the same as for the Popen constructor. Example:
129
Florent Xicluna4886d242010-03-08 13:27:26 +0000130 >>> retcode = subprocess.call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131
Peter Astrand454f7672005-01-01 09:36:35 +0000132check_call(*popenargs, **kwargs):
133 Run command with arguments. Wait for command to complete. If the
134 exit code was zero then return, otherwise raise
135 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000137
138 The arguments are the same as for the Popen constructor. Example:
139
Florent Xicluna4886d242010-03-08 13:27:26 +0000140 >>> subprocess.check_call(["ls", "-l"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000141 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142
Brett Cannona23810f2008-05-26 19:04:21 +0000143getstatusoutput(cmd):
144 Return (status, output) of executing cmd in a shell.
145
Tim Golden60798142013-11-05 12:57:25 +0000146 Execute the string 'cmd' in a shell with 'check_output' and
147 return a 2-tuple (status, output). Universal newlines mode is used,
148 meaning that the result with be decoded to a string.
149
150 A trailing newline is stripped from the output.
151 The exit status for the command can be interpreted
152 according to the rules for the function 'wait'. Example:
Brett Cannona23810f2008-05-26 19:04:21 +0000153
Brett Cannona23810f2008-05-26 19:04:21 +0000154 >>> subprocess.getstatusoutput('ls /bin/ls')
155 (0, '/bin/ls')
156 >>> subprocess.getstatusoutput('cat /bin/junk')
157 (256, 'cat: /bin/junk: No such file or directory')
158 >>> subprocess.getstatusoutput('/bin/junk')
159 (256, 'sh: /bin/junk: not found')
160
161getoutput(cmd):
162 Return output (stdout or stderr) of executing cmd in a shell.
163
164 Like getstatusoutput(), except the exit status is ignored and the return
165 value is a string containing the command's output. Example:
166
Brett Cannona23810f2008-05-26 19:04:21 +0000167 >>> subprocess.getoutput('ls /bin/ls')
168 '/bin/ls'
169
Georg Brandlf9734072008-12-07 15:30:06 +0000170check_output(*popenargs, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700171 Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000172
Georg Brandl2708f3a2009-12-20 14:38:23 +0000173 If the exit code was non-zero it raises a CalledProcessError. The
174 CalledProcessError object will have the return code in the returncode
175 attribute and output in the output attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000176
Georg Brandl2708f3a2009-12-20 14:38:23 +0000177 The arguments are the same as for the Popen constructor. Example:
Georg Brandlf9734072008-12-07 15:30:06 +0000178
Georg Brandl2708f3a2009-12-20 14:38:23 +0000179 >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandlf9734072008-12-07 15:30:06 +0000180
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300181 There is an additional optional argument, "input", allowing you to
182 pass a string to the subprocess's stdin. If you use this argument
183 you may not also use the Popen constructor's "stdin" argument.
Brett Cannona23810f2008-05-26 19:04:21 +0000184
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400185 If universal_newlines is set to True, the "input" argument must
186 be a string rather than bytes, and the return value will be a string.
187
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188Exceptions
189----------
190Exceptions raised in the child process, before the new program has
191started to execute, will be re-raised in the parent. Additionally,
192the exception object will have one extra attribute called
193'child_traceback', which is a string containing traceback information
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300194from the child's point of view.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195
196The most common exception raised is OSError. This occurs, for
197example, when trying to execute a non-existent file. Applications
198should prepare for OSErrors.
199
200A ValueError will be raised if Popen is called with invalid arguments.
201
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400202Exceptions defined within this module inherit from SubprocessError.
203check_call() and check_output() will raise CalledProcessError if the
Gregory P. Smithb4039aa2011-03-14 14:16:20 -0400204called process returns a non-zero return code. TimeoutExpired
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400205be raised if a timeout was specified and expired.
Peter Astrand454f7672005-01-01 09:36:35 +0000206
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207
208Security
209--------
210Unlike some other popen functions, this implementation will never call
211/bin/sh implicitly. This means that all characters, including shell
212metacharacters, can safely be passed to child processes.
213
214
215Popen objects
216=============
217Instances of the Popen class have the following methods:
218
219poll()
220 Check if child process has terminated. Returns returncode
221 attribute.
222
223wait()
224 Wait for child process to terminate. Returns returncode attribute.
225
226communicate(input=None)
227 Interact with process: Send data to stdin. Read data from stdout
228 and stderr, until end-of-file is reached. Wait for process to
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400229 terminate. The optional input argument should be data to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 sent to the child process, or None, if no data should be sent to
Steve Dower050acae2016-09-06 20:16:17 -0700231 the child. If the Popen instance was constructed in text mode, the
232 input argument should be a string. Otherwise, it should be bytes.
Tim Peterse718f612004-10-12 21:51:32 +0000233
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 communicate() returns a tuple (stdout, stderr).
235
236 Note: The data read is buffered in memory, so do not use this
237 method if the data size is large or unlimited.
238
239The following attributes are also available:
240
241stdin
242 If the stdin argument is PIPE, this attribute is a file object
243 that provides input to the child process. Otherwise, it is None.
244
245stdout
246 If the stdout argument is PIPE, this attribute is a file object
247 that provides output from the child process. Otherwise, it is
248 None.
249
250stderr
251 If the stderr argument is PIPE, this attribute is file object that
252 provides error output from the child process. Otherwise, it is
253 None.
254
255pid
256 The process ID of the child process.
257
258returncode
259 The child return code. A None value indicates that the process
260 hasn't terminated yet. A negative value -N indicates that the
Gregory P. Smithf5604852010-12-13 06:45:02 +0000261 child was terminated by signal N (POSIX only).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262
263
264Replacing older functions with the subprocess module
265====================================================
266In this section, "a ==> b" means that b can be used as a replacement
267for a.
268
269Note: All functions in this section fail (more or less) silently if
270the executed program cannot be found; this module raises an OSError
271exception.
272
273In the following examples, we assume that the subprocess module is
274imported with "from subprocess import *".
275
276
277Replacing /bin/sh shell backquote
278---------------------------------
279output=`mycmd myarg`
280==>
281output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
282
283
284Replacing shell pipe line
285-------------------------
286output=`dmesg | grep hda`
287==>
288p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000289p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290output = p2.communicate()[0]
291
292
293Replacing os.system()
294---------------------
295sts = os.system("mycmd" + " myarg")
296==>
297p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299
300Note:
301
302* Calling the program through the shell is usually not required.
303
304* It's easier to look at the returncode attribute than the
305 exitstatus.
306
307A more real-world example would look like this:
308
309try:
310 retcode = call("mycmd" + " myarg", shell=True)
311 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000312 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000314 print("Child returned", retcode, file=sys.stderr)
315except OSError as e:
316 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317
318
319Replacing os.spawn*
320-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000321P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322
323pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
324==>
325pid = Popen(["/bin/mycmd", "myarg"]).pid
326
327
328P_WAIT example:
329
330retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
331==>
332retcode = call(["/bin/mycmd", "myarg"])
333
334
Tim Peterse718f612004-10-12 21:51:32 +0000335Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336
337os.spawnvp(os.P_NOWAIT, path, args)
338==>
339Popen([path] + args[1:])
340
341
Tim Peterse718f612004-10-12 21:51:32 +0000342Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343
344os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
345==>
346Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347"""
348
349import sys
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700350_mswindows = (sys.platform == "win32")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000352import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353import os
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400354import time
Christian Heimesa342c012008-04-20 21:01:16 +0000355import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000356import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000357import warnings
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200358import errno
Victor Stinnerae586492014-09-02 23:18:25 +0200359from time import monotonic as _time
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360
Peter Astrand454f7672005-01-01 09:36:35 +0000361# Exception classes used by this module.
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400362class SubprocessError(Exception): pass
363
364
365class CalledProcessError(SubprocessError):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +0000366 """Raised when a check_call() or check_output() process returns non-zero.
367
368 The exit status will be stored in the returncode attribute, negative
369 if it represents a signal number.
370
Georg Brandlf9734072008-12-07 15:30:06 +0000371 check_output() will also store the output in the output attribute.
372 """
Gregory P. Smith6e730002015-04-14 16:14:25 -0700373 def __init__(self, returncode, cmd, output=None, stderr=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 self.returncode = returncode
375 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000376 self.output = output
Gregory P. Smith6e730002015-04-14 16:14:25 -0700377 self.stderr = stderr
378
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000379 def __str__(self):
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +0000380 if self.returncode and self.returncode < 0:
381 try:
382 return "Command '%s' died with %r." % (
383 self.cmd, signal.Signals(-self.returncode))
384 except ValueError:
385 return "Command '%s' died with unknown signal %d." % (
386 self.cmd, -self.returncode)
387 else:
388 return "Command '%s' returned non-zero exit status %d." % (
389 self.cmd, self.returncode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000390
Gregory P. Smith6e730002015-04-14 16:14:25 -0700391 @property
392 def stdout(self):
393 """Alias for output attribute, to match stderr"""
394 return self.output
395
396 @stdout.setter
397 def stdout(self, value):
398 # There's no obvious reason to set this, but allow it anyway so
399 # .stdout is a transparent alias for .output
400 self.output = value
401
Peter Astrand454f7672005-01-01 09:36:35 +0000402
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400403class TimeoutExpired(SubprocessError):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400404 """This exception is raised when the timeout expires while waiting for a
405 child process.
406 """
Gregory P. Smith6e730002015-04-14 16:14:25 -0700407 def __init__(self, cmd, timeout, output=None, stderr=None):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400408 self.cmd = cmd
Reid Kleckner2b228f02011-03-16 16:57:54 -0400409 self.timeout = timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400410 self.output = output
Gregory P. Smith6e730002015-04-14 16:14:25 -0700411 self.stderr = stderr
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400412
413 def __str__(self):
414 return ("Command '%s' timed out after %s seconds" %
415 (self.cmd, self.timeout))
416
Gregory P. Smith6e730002015-04-14 16:14:25 -0700417 @property
418 def stdout(self):
419 return self.output
420
421 @stdout.setter
422 def stdout(self, value):
423 # There's no obvious reason to set this, but allow it anyway so
424 # .stdout is a transparent alias for .output
425 self.output = value
426
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400427
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700428if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 import threading
430 import msvcrt
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200431 import _winapi
Brian Curtin1ce6b582010-04-24 16:19:22 +0000432 class STARTUPINFO:
433 dwFlags = 0
434 hStdInput = None
435 hStdOutput = None
436 hStdError = None
437 wShowWindow = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -0700439 import _posixsubprocess
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100440 import select
441 import selectors
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700442 try:
443 import threading
444 except ImportError:
445 import dummy_threading as threading
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000446
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000447 # When select or poll has indicated that the file is writable,
448 # we can write up to _PIPE_BUF bytes without risk of blocking.
449 # POSIX defines PIPE_BUF as >= 512.
450 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
451
Charles-François Natali3a4586a2013-11-08 19:56:59 +0100452 # poll/select have the advantage of not requiring any extra file
453 # descriptor, contrarily to epoll/kqueue (also, they require a single
454 # syscall).
455 if hasattr(selectors, 'PollSelector'):
456 _PopenSelector = selectors.PollSelector
457 else:
458 _PopenSelector = selectors.SelectSelector
459
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000460
Brett Cannona23810f2008-05-26 19:04:21 +0000461__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Gregory P. Smith6e730002015-04-14 16:14:25 -0700462 "getoutput", "check_output", "run", "CalledProcessError", "DEVNULL",
463 "SubprocessError", "TimeoutExpired", "CompletedProcess"]
Gregory P. Smithace55862015-04-07 15:57:54 -0700464 # NOTE: We intentionally exclude list2cmdline as it is
465 # considered an internal implementation detail. issue10838.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700467if _mswindows:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200468 from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
469 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
470 STD_ERROR_HANDLE, SW_HIDE,
471 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Brian Curtin5d9deaa2011-04-29 16:24:07 -0500472
Brian Curtin08fd8d92011-04-29 16:11:30 -0500473 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500474 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
475 "STD_ERROR_HANDLE", "SW_HIDE",
Martin Panter528619b2016-04-16 23:42:37 +0000476 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW",
477 "STARTUPINFO"])
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200478
479 class Handle(int):
480 closed = False
481
482 def Close(self, CloseHandle=_winapi.CloseHandle):
483 if not self.closed:
484 self.closed = True
485 CloseHandle(self)
486
487 def Detach(self):
488 if not self.closed:
489 self.closed = True
490 return int(self)
491 raise ValueError("already closed")
492
493 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300494 return "%s(%d)" % (self.__class__.__name__, int(self))
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200495
496 __del__ = Close
497 __str__ = __repr__
498
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200500# This lists holds Popen instances for which the underlying process had not
501# exited at the time its __del__ method got called: those processes are wait()ed
502# for synchronously from _cleanup() when a new Popen object is created, to avoid
503# zombie processes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504_active = []
505
506def _cleanup():
507 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000508 res = inst._internal_poll(_deadstate=sys.maxsize)
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200509 if res is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000510 try:
511 _active.remove(inst)
512 except ValueError:
513 # This can happen if two threads create a new Popen instance.
514 # It's harmless that it was already removed, so ignore.
515 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516
517PIPE = -1
518STDOUT = -2
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200519DEVNULL = -3
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200522# XXX This function is only used by multiprocessing and the test suite,
523# but it's here so that it can be imported when Python is compiled without
524# threads.
525
Victor Stinner9def2842016-01-18 12:15:08 +0100526def _optim_args_from_interpreter_flags():
527 """Return a list of command-line arguments reproducing the current
528 optimization settings in sys.flags."""
529 args = []
530 value = sys.flags.optimize
531 if value > 0:
532 args.append('-' + 'O' * value)
533 return args
534
535
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200536def _args_from_interpreter_flags():
537 """Return a list of command-line arguments reproducing the current
538 settings in sys.flags and sys.warnoptions."""
539 flag_opt_map = {
540 'debug': 'd',
541 # 'inspect': 'i',
542 # 'interactive': 'i',
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200543 'dont_write_bytecode': 'B',
544 'no_user_site': 's',
545 'no_site': 'S',
546 'ignore_environment': 'E',
547 'verbose': 'v',
548 'bytes_warning': 'b',
549 'quiet': 'q',
Victor Stinner9def2842016-01-18 12:15:08 +0100550 # -O is handled in _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200551 }
Victor Stinner9def2842016-01-18 12:15:08 +0100552 args = _optim_args_from_interpreter_flags()
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200553 for flag, opt in flag_opt_map.items():
554 v = getattr(sys.flags, flag)
555 if v > 0:
556 args.append('-' + opt * v)
557 for opt in sys.warnoptions:
558 args.append('-W' + opt)
559 return args
560
561
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400562def call(*popenargs, timeout=None, **kwargs):
563 """Run command with arguments. Wait for command to complete or
564 timeout, then return the returncode attribute.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
566 The arguments are the same as for the Popen constructor. Example:
567
568 retcode = call(["ls", "-l"])
569 """
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200570 with Popen(*popenargs, **kwargs) as p:
571 try:
572 return p.wait(timeout=timeout)
573 except:
574 p.kill()
575 p.wait()
576 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577
578
Peter Astrand454f7672005-01-01 09:36:35 +0000579def check_call(*popenargs, **kwargs):
580 """Run command with arguments. Wait for command to complete. If
581 the exit code was zero then return, otherwise raise
582 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000583 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000584
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400585 The arguments are the same as for the call function. Example:
Peter Astrand454f7672005-01-01 09:36:35 +0000586
587 check_call(["ls", "-l"])
588 """
589 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000590 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000591 cmd = kwargs.get("args")
592 if cmd is None:
593 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000594 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000595 return 0
596
597
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400598def check_output(*popenargs, timeout=None, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700599 r"""Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000600
601 If the exit code was non-zero it raises a CalledProcessError. The
602 CalledProcessError object will have the return code in the returncode
603 attribute and output in the output attribute.
604
605 The arguments are the same as for the Popen constructor. Example:
606
607 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000608 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000609
610 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000611 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000612
613 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000614 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000615 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000616 b'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith91110f52013-03-19 23:25:16 -0700617
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300618 There is an additional optional argument, "input", allowing you to
619 pass a string to the subprocess's stdin. If you use this argument
620 you may not also use the Popen constructor's "stdin" argument, as
621 it too will be used internally. Example:
622
623 >>> check_output(["sed", "-e", "s/foo/bar/"],
624 ... input=b"when in the course of fooman events\n")
625 b'when in the course of barman events\n'
626
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -0400627 If universal_newlines=True is passed, the "input" argument must be a
628 string and the return value will be a string rather than bytes.
Georg Brandlf9734072008-12-07 15:30:06 +0000629 """
630 if 'stdout' in kwargs:
631 raise ValueError('stdout argument not allowed, it will be overridden.')
Gregory P. Smith6e730002015-04-14 16:14:25 -0700632
633 if 'input' in kwargs and kwargs['input'] is None:
634 # Explicitly passing input=None was previously equivalent to passing an
635 # empty string. That is maintained here for backwards compatibility.
636 kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''
637
638 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
639 **kwargs).stdout
640
641
642class CompletedProcess(object):
643 """A process that has finished running.
644
645 This is returned by run().
646
647 Attributes:
648 args: The list or str args passed to run().
649 returncode: The exit code of the process, negative for signals.
650 stdout: The standard output (None if not captured).
651 stderr: The standard error (None if not captured).
652 """
653 def __init__(self, args, returncode, stdout=None, stderr=None):
654 self.args = args
655 self.returncode = returncode
656 self.stdout = stdout
657 self.stderr = stderr
658
659 def __repr__(self):
660 args = ['args={!r}'.format(self.args),
661 'returncode={!r}'.format(self.returncode)]
662 if self.stdout is not None:
663 args.append('stdout={!r}'.format(self.stdout))
664 if self.stderr is not None:
665 args.append('stderr={!r}'.format(self.stderr))
666 return "{}({})".format(type(self).__name__, ', '.join(args))
667
668 def check_returncode(self):
669 """Raise CalledProcessError if the exit code is non-zero."""
670 if self.returncode:
671 raise CalledProcessError(self.returncode, self.args, self.stdout,
672 self.stderr)
673
674
675def run(*popenargs, input=None, timeout=None, check=False, **kwargs):
676 """Run command with arguments and return a CompletedProcess instance.
677
678 The returned instance will have attributes args, returncode, stdout and
679 stderr. By default, stdout and stderr are not captured, and those attributes
680 will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
681
682 If check is True and the exit code was non-zero, it raises a
683 CalledProcessError. The CalledProcessError object will have the return code
684 in the returncode attribute, and output & stderr attributes if those streams
685 were captured.
686
687 If timeout is given, and the process takes too long, a TimeoutExpired
688 exception will be raised.
689
690 There is an optional argument "input", allowing you to
691 pass a string to the subprocess's stdin. If you use this argument
692 you may not also use the Popen constructor's "stdin" argument, as
693 it will be used internally.
694
695 The other arguments are the same as for the Popen constructor.
696
697 If universal_newlines=True is passed, the "input" argument must be a
698 string and stdout/stderr in the returned object will be strings rather than
699 bytes.
700 """
701 if input is not None:
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300702 if 'stdin' in kwargs:
703 raise ValueError('stdin and input arguments may not both be used.')
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300704 kwargs['stdin'] = PIPE
Gregory P. Smith6e730002015-04-14 16:14:25 -0700705
706 with Popen(*popenargs, **kwargs) as process:
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200707 try:
Gregory P. Smith6e730002015-04-14 16:14:25 -0700708 stdout, stderr = process.communicate(input, timeout=timeout)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200709 except TimeoutExpired:
710 process.kill()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700711 stdout, stderr = process.communicate()
712 raise TimeoutExpired(process.args, timeout, output=stdout,
713 stderr=stderr)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200714 except:
715 process.kill()
716 process.wait()
717 raise
718 retcode = process.poll()
Gregory P. Smith6e730002015-04-14 16:14:25 -0700719 if check and retcode:
720 raise CalledProcessError(retcode, process.args,
721 output=stdout, stderr=stderr)
722 return CompletedProcess(process.args, retcode, stdout, stderr)
Peter Astrand454f7672005-01-01 09:36:35 +0000723
724
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725def list2cmdline(seq):
726 """
727 Translate a sequence of arguments into a command line
728 string, using the same rules as the MS C runtime:
729
730 1) Arguments are delimited by white space, which is either a
731 space or a tab.
732
733 2) A string surrounded by double quotation marks is
734 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000735 contained within. A quoted string can be embedded in an
736 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737
738 3) A double quotation mark preceded by a backslash is
739 interpreted as a literal double quotation mark.
740
741 4) Backslashes are interpreted literally, unless they
742 immediately precede a double quotation mark.
743
744 5) If backslashes immediately precede a double quotation mark,
745 every pair of backslashes is interpreted as a literal
746 backslash. If the number of backslashes is odd, the last
747 backslash escapes the next double quotation mark as
748 described in rule 3.
749 """
750
751 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000752 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
753 # or search http://msdn.microsoft.com for
754 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 result = []
756 needquote = False
757 for arg in seq:
758 bs_buf = []
759
760 # Add a space to separate this argument from the others
761 if result:
762 result.append(' ')
763
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000764 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 if needquote:
766 result.append('"')
767
768 for c in arg:
769 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000770 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771 bs_buf.append(c)
772 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000773 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774 result.append('\\' * len(bs_buf)*2)
775 bs_buf = []
776 result.append('\\"')
777 else:
778 # Normal char
779 if bs_buf:
780 result.extend(bs_buf)
781 bs_buf = []
782 result.append(c)
783
Christian Heimesfdab48e2008-01-20 09:06:41 +0000784 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 if bs_buf:
786 result.extend(bs_buf)
787
788 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000789 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 result.append('"')
791
792 return ''.join(result)
793
794
Brett Cannona23810f2008-05-26 19:04:21 +0000795# Various tools for executing commands and looking at their output and status.
796#
Brett Cannona23810f2008-05-26 19:04:21 +0000797
798def getstatusoutput(cmd):
Tim Golden60798142013-11-05 12:57:25 +0000799 """ Return (status, output) of executing cmd in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000800
Tim Golden60798142013-11-05 12:57:25 +0000801 Execute the string 'cmd' in a shell with 'check_output' and
Steve Dower050acae2016-09-06 20:16:17 -0700802 return a 2-tuple (status, output). The locale encoding is used
803 to decode the output and process newlines.
Tim Golden60798142013-11-05 12:57:25 +0000804
805 A trailing newline is stripped from the output.
806 The exit status for the command can be interpreted
807 according to the rules for the function 'wait'. Example:
Brett Cannona23810f2008-05-26 19:04:21 +0000808
809 >>> import subprocess
810 >>> subprocess.getstatusoutput('ls /bin/ls')
811 (0, '/bin/ls')
812 >>> subprocess.getstatusoutput('cat /bin/junk')
813 (256, 'cat: /bin/junk: No such file or directory')
814 >>> subprocess.getstatusoutput('/bin/junk')
815 (256, 'sh: /bin/junk: not found')
816 """
Tim Goldene0041752013-11-03 12:53:17 +0000817 try:
818 data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
819 status = 0
820 except CalledProcessError as ex:
821 data = ex.output
822 status = ex.returncode
823 if data[-1:] == '\n':
824 data = data[:-1]
825 return status, data
Brett Cannona23810f2008-05-26 19:04:21 +0000826
827def getoutput(cmd):
828 """Return output (stdout or stderr) of executing cmd in a shell.
829
830 Like getstatusoutput(), except the exit status is ignored and the return
831 value is a string containing the command's output. Example:
832
833 >>> import subprocess
834 >>> subprocess.getoutput('ls /bin/ls')
835 '/bin/ls'
836 """
837 return getstatusoutput(cmd)[1]
838
839
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000840_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000841
842
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843class Popen(object):
Serhiy Storchaka72e77612014-02-10 19:20:22 +0200844
845 _child_created = False # Set here since __del__ checks it
846
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700847 def __init__(self, args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000849 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
850 shell=False, cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000851 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000852 restore_signals=True, start_new_session=False,
Steve Dower050acae2016-09-06 20:16:17 -0700853 pass_fds=(), *, encoding=None, errors=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 """Create new Popen instance."""
855 _cleanup()
Gregory P. Smithd65ba512014-04-23 00:27:17 -0700856 # Held while anything is calling waitpid before returncode has been
857 # updated to prevent clobbering returncode if wait() or poll() are
858 # called from multiple threads at once. After acquiring the lock,
859 # code must re-check self.returncode to see if another thread just
860 # finished a waitpid() call.
861 self._waitpid_lock = threading.Lock()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400863 self._input = None
864 self._communication_started = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000865 if bufsize is None:
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700866 bufsize = -1 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000867 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000868 raise TypeError("bufsize must be an integer")
869
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700870 if _mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000871 if preexec_fn is not None:
872 raise ValueError("preexec_fn is not supported on Windows "
873 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000874 any_stdio_set = (stdin is not None or stdout is not None or
875 stderr is not None)
876 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
877 if any_stdio_set:
878 close_fds = False
879 else:
880 close_fds = True
881 elif close_fds and any_stdio_set:
882 raise ValueError(
883 "close_fds is not supported on Windows platforms"
884 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885 else:
886 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000887 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
888 close_fds = True
889 if pass_fds and not close_fds:
890 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
891 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000892 if startupinfo is not None:
893 raise ValueError("startupinfo is only supported on Windows "
894 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000896 raise ValueError("creationflags is only supported on Windows "
897 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400899 self.args = args
Tim Peterse718f612004-10-12 21:51:32 +0000900 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000901 self.stdout = None
902 self.stderr = None
903 self.pid = None
904 self.returncode = None
905 self.universal_newlines = universal_newlines
Steve Dower050acae2016-09-06 20:16:17 -0700906 self.encoding = encoding
907 self.errors = errors
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908
909 # Input and output objects. The general principle is like
910 # this:
911 #
912 # Parent Child
913 # ------ -----
914 # p2cwrite ---stdin---> p2cread
915 # c2pread <--stdout--- c2pwrite
916 # errread <--stderr--- errwrite
917 #
918 # On POSIX, the child objects are file descriptors. On
919 # Windows, these are Windows file handles. The parent objects
920 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000921 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000923
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924 (p2cread, p2cwrite,
925 c2pread, c2pwrite,
926 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
927
Antoine Pitrouc9982322011-01-04 19:07:07 +0000928 # We wrap OS handles *before* launching the child, otherwise a
929 # quickly terminating child could make our fds unwrappable
930 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -0700932 if _mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000933 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000934 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000935 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000936 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000937 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000938 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000939
Steve Dower050acae2016-09-06 20:16:17 -0700940 text_mode = encoding or errors or universal_newlines
Tim Peterse718f612004-10-12 21:51:32 +0000941
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700942 self._closed_child_pipe_fds = False
Steve Dower050acae2016-09-06 20:16:17 -0700943
Antoine Pitrouc9982322011-01-04 19:07:07 +0000944 try:
Steve Dower050acae2016-09-06 20:16:17 -0700945 if p2cwrite != -1:
946 self.stdin = io.open(p2cwrite, 'wb', bufsize)
947 if text_mode:
948 self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
949 line_buffering=(bufsize == 1),
950 encoding=encoding, errors=errors)
951 if c2pread != -1:
952 self.stdout = io.open(c2pread, 'rb', bufsize)
953 if text_mode:
954 self.stdout = io.TextIOWrapper(self.stdout,
955 encoding=encoding, errors=errors)
956 if errread != -1:
957 self.stderr = io.open(errread, 'rb', bufsize)
958 if text_mode:
959 self.stderr = io.TextIOWrapper(self.stderr,
960 encoding=encoding, errors=errors)
961
Antoine Pitrouc9982322011-01-04 19:07:07 +0000962 self._execute_child(args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300963 pass_fds, cwd, env,
Antoine Pitrouc9982322011-01-04 19:07:07 +0000964 startupinfo, creationflags, shell,
965 p2cread, p2cwrite,
966 c2pread, c2pwrite,
967 errread, errwrite,
968 restore_signals, start_new_session)
969 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800970 # Cleanup if the child failed starting.
971 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000972 try:
973 f.close()
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200974 except OSError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800975 pass # Ignore EBADF or other errors.
976
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700977 if not self._closed_child_pipe_fds:
978 to_close = []
979 if stdin == PIPE:
980 to_close.append(p2cread)
981 if stdout == PIPE:
982 to_close.append(c2pwrite)
983 if stderr == PIPE:
984 to_close.append(errwrite)
985 if hasattr(self, '_devnull'):
986 to_close.append(self._devnull)
987 for fd in to_close:
988 try:
989 os.close(fd)
Gregory P. Smith22ba31a2013-06-15 18:14:56 -0700990 except OSError:
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700991 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800992
Antoine Pitrouc9982322011-01-04 19:07:07 +0000993 raise
994
Steve Dower050acae2016-09-06 20:16:17 -0700995 def _translate_newlines(self, data, encoding, errors):
996 data = data.decode(encoding, errors)
Andrew Svetlov82860712012-08-19 22:13:41 +0300997 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998
Brian Curtin79cdb662010-12-03 02:46:02 +0000999 def __enter__(self):
1000 return self
1001
1002 def __exit__(self, type, value, traceback):
1003 if self.stdout:
1004 self.stdout.close()
1005 if self.stderr:
1006 self.stderr.close()
Serhiy Storchakaab900c22015-02-28 12:43:08 +02001007 try: # Flushing a BufferedWriter may raise an error
1008 if self.stdin:
1009 self.stdin.close()
1010 finally:
1011 # Wait for the process to terminate, to avoid zombies.
1012 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001013
Serhiy Storchaka72e77612014-02-10 19:20:22 +02001014 def __del__(self, _maxsize=sys.maxsize):
1015 if not self._child_created:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001016 # We didn't get to successfully create a child process.
1017 return
Victor Stinner5a48e212016-05-20 12:11:15 +02001018 if self.returncode is None:
Victor Stinnerc206f1e2016-06-14 16:42:59 +02001019 # Not reading subprocess exit status creates a zombi process which
1020 # is only destroyed at the parent python process exit
1021 warnings.warn("subprocess %s is still running" % self.pid,
1022 ResourceWarning, source=self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +00001024 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001026 # Child is still running, keep us alive until we can wait on it.
1027 _active.append(self)
1028
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001029 def _get_devnull(self):
1030 if not hasattr(self, '_devnull'):
1031 self._devnull = os.open(os.devnull, os.O_RDWR)
1032 return self._devnull
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001033
Victor Stinnera5e881d2015-01-14 17:07:59 +01001034 def _stdin_write(self, input):
1035 if input:
1036 try:
1037 self.stdin.write(input)
1038 except BrokenPipeError:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001039 pass # communicate() must ignore broken pipe errors.
Victor Stinnera5e881d2015-01-14 17:07:59 +01001040 except OSError as e:
1041 if e.errno == errno.EINVAL and self.poll() is not None:
1042 # Issue #19612: On Windows, stdin.write() fails with EINVAL
1043 # if the process already exited before the write
1044 pass
1045 else:
1046 raise
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001047 try:
1048 self.stdin.close()
1049 except BrokenPipeError:
1050 pass # communicate() must ignore broken pipe errors.
1051 except OSError as e:
1052 if e.errno == errno.EINVAL and self.poll() is not None:
1053 pass
1054 else:
1055 raise
Victor Stinnera5e881d2015-01-14 17:07:59 +01001056
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001057 def communicate(self, input=None, timeout=None):
Peter Astrand23109f02005-03-03 20:28:59 +00001058 """Interact with process: Send data to stdin. Read data from
1059 stdout and stderr, until end-of-file is reached. Wait for
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -04001060 process to terminate.
Tim Peterseba28be2005-03-28 01:08:02 +00001061
Andrew Kuchling4f7b0c32014-04-14 15:08:18 -04001062 The optional "input" argument should be data to be sent to the
1063 child process (if self.universal_newlines is True, this should
1064 be a string; if it is False, "input" should be bytes), or
1065 None, if no data should be sent to the child.
1066
1067 communicate() returns a tuple (stdout, stderr). These will be
1068 bytes or, if self.universal_newlines was True, a string.
1069 """
Peter Astrand23109f02005-03-03 20:28:59 +00001070
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001071 if self._communication_started and input:
1072 raise ValueError("Cannot send input after starting communication")
1073
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001074 # Optimization: If we are not worried about timeouts, we haven't
1075 # started communicating, and we have one or zero pipes, using select()
1076 # or threads is unnecessary.
Victor Stinner7a8d0812011-04-05 13:13:08 +02001077 if (timeout is None and not self._communication_started and
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001078 [self.stdin, self.stdout, self.stderr].count(None) >= 2):
Tim Peterseba28be2005-03-28 01:08:02 +00001079 stdout = None
1080 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +00001081 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +01001082 self._stdin_write(input)
Peter Astrand23109f02005-03-03 20:28:59 +00001083 elif self.stdout:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001084 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001085 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +00001086 elif self.stderr:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001087 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001088 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +00001089 self.wait()
Victor Stinner7a8d0812011-04-05 13:13:08 +02001090 else:
1091 if timeout is not None:
Victor Stinner949d8c92012-05-30 13:30:32 +02001092 endtime = _time() + timeout
Victor Stinner7a8d0812011-04-05 13:13:08 +02001093 else:
1094 endtime = None
Tim Peterseba28be2005-03-28 01:08:02 +00001095
Victor Stinner7a8d0812011-04-05 13:13:08 +02001096 try:
1097 stdout, stderr = self._communicate(input, endtime, timeout)
1098 finally:
1099 self._communication_started = True
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001100
Victor Stinner7a8d0812011-04-05 13:13:08 +02001101 sts = self.wait(timeout=self._remaining_time(endtime))
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001102
1103 return (stdout, stderr)
Peter Astrand23109f02005-03-03 20:28:59 +00001104
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001106 def poll(self):
1107 return self._internal_poll()
1108
1109
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001110 def _remaining_time(self, endtime):
1111 """Convenience for _communicate when computing timeouts."""
1112 if endtime is None:
1113 return None
1114 else:
Victor Stinner949d8c92012-05-30 13:30:32 +02001115 return endtime - _time()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001116
1117
Reid Kleckner2b228f02011-03-16 16:57:54 -04001118 def _check_timeout(self, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001119 """Convenience for checking if a timeout has expired."""
1120 if endtime is None:
1121 return
Victor Stinner949d8c92012-05-30 13:30:32 +02001122 if _time() > endtime:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001123 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001124
1125
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -07001126 if _mswindows:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001127 #
1128 # Windows methods
1129 #
1130 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001131 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001132 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1133 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001134 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001135 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +00001136
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001137 p2cread, p2cwrite = -1, -1
1138 c2pread, c2pwrite = -1, -1
1139 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140
Peter Astrandd38ddf42005-02-10 08:32:50 +00001141 if stdin is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001142 p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001143 if p2cread is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001144 p2cread, _ = _winapi.CreatePipe(None, 0)
1145 p2cread = Handle(p2cread)
1146 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001147 elif stdin == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001148 p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
1149 p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001150 elif stdin == DEVNULL:
1151 p2cread = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001152 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001153 p2cread = msvcrt.get_osfhandle(stdin)
1154 else:
1155 # Assuming file-like object
1156 p2cread = msvcrt.get_osfhandle(stdin.fileno())
1157 p2cread = self._make_inheritable(p2cread)
1158
Peter Astrandd38ddf42005-02-10 08:32:50 +00001159 if stdout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001160 c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001161 if c2pwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001162 _, c2pwrite = _winapi.CreatePipe(None, 0)
1163 c2pwrite = Handle(c2pwrite)
1164 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001165 elif stdout == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001166 c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
1167 c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001168 elif stdout == DEVNULL:
1169 c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001170 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 c2pwrite = msvcrt.get_osfhandle(stdout)
1172 else:
1173 # Assuming file-like object
1174 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
1175 c2pwrite = self._make_inheritable(c2pwrite)
1176
Peter Astrandd38ddf42005-02-10 08:32:50 +00001177 if stderr is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001178 errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001179 if errwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001180 _, errwrite = _winapi.CreatePipe(None, 0)
1181 errwrite = Handle(errwrite)
1182 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001183 elif stderr == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001184 errread, errwrite = _winapi.CreatePipe(None, 0)
1185 errread, errwrite = Handle(errread), Handle(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001186 elif stderr == STDOUT:
1187 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001188 elif stderr == DEVNULL:
1189 errwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001190 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001191 errwrite = msvcrt.get_osfhandle(stderr)
1192 else:
1193 # Assuming file-like object
1194 errwrite = msvcrt.get_osfhandle(stderr.fileno())
1195 errwrite = self._make_inheritable(errwrite)
1196
1197 return (p2cread, p2cwrite,
1198 c2pread, c2pwrite,
1199 errread, errwrite)
1200
1201
1202 def _make_inheritable(self, handle):
1203 """Return a duplicate of handle, which is inheritable"""
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001204 h = _winapi.DuplicateHandle(
1205 _winapi.GetCurrentProcess(), handle,
1206 _winapi.GetCurrentProcess(), 0, 1,
1207 _winapi.DUPLICATE_SAME_ACCESS)
1208 return Handle(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001209
1210
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001211 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001212 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213 startupinfo, creationflags, shell,
1214 p2cread, p2cwrite,
1215 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001216 errread, errwrite,
1217 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001218 """Execute program (MS Windows version)"""
1219
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001220 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001221
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001222 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001223 args = list2cmdline(args)
1224
Peter Astrandc1d65362004-11-07 14:30:34 +00001225 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +00001226 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001227 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +00001228 if -1 not in (p2cread, c2pwrite, errwrite):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001229 startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +00001230 startupinfo.hStdInput = p2cread
1231 startupinfo.hStdOutput = c2pwrite
1232 startupinfo.hStdError = errwrite
1233
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001234 if shell:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001235 startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
1236 startupinfo.wShowWindow = _winapi.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001237 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +00001238 args = '{} /c "{}"'.format (comspec, args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001240 # Start the process
1241 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001242 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +00001243 # no special security
1244 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001245 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +00001246 creationflags,
1247 env,
1248 cwd,
1249 startupinfo)
Tim Goldenad537f22010-08-08 11:18:16 +00001250 finally:
1251 # Child is launched. Close the parent's copy of those pipe
1252 # handles that only the child should have open. You need
1253 # to make sure that no handles to the write end of the
1254 # output pipe are maintained in this process or else the
1255 # pipe will not close when the child process exits and the
1256 # ReadFile will hang.
1257 if p2cread != -1:
1258 p2cread.Close()
1259 if c2pwrite != -1:
1260 c2pwrite.Close()
1261 if errwrite != -1:
1262 errwrite.Close()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001263 if hasattr(self, '_devnull'):
1264 os.close(self._devnull)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001265
1266 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001267 self._child_created = True
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001268 self._handle = Handle(hp)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001269 self.pid = pid
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001270 _winapi.CloseHandle(ht)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001271
Brett Cannon84df1e62010-05-14 00:33:40 +00001272 def _internal_poll(self, _deadstate=None,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001273 _WaitForSingleObject=_winapi.WaitForSingleObject,
1274 _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
1275 _GetExitCodeProcess=_winapi.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001276 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001277 attribute.
1278
1279 This method is called by __del__, so it can only refer to objects
1280 in its local scope.
1281
1282 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001283 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001284 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1285 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001286 return self.returncode
1287
1288
Reid Kleckner2b228f02011-03-16 16:57:54 -04001289 def wait(self, timeout=None, endtime=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001290 """Wait for child process to terminate. Returns returncode
1291 attribute."""
Reid Kleckner2b228f02011-03-16 16:57:54 -04001292 if endtime is not None:
1293 timeout = self._remaining_time(endtime)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001294 if timeout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001295 timeout_millis = _winapi.INFINITE
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001296 else:
Reid Kleckner91156ff2011-03-21 10:06:10 -07001297 timeout_millis = int(timeout * 1000)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001298 if self.returncode is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001299 result = _winapi.WaitForSingleObject(self._handle,
1300 timeout_millis)
1301 if result == _winapi.WAIT_TIMEOUT:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001302 raise TimeoutExpired(self.args, timeout)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001303 self.returncode = _winapi.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001304 return self.returncode
1305
1306
1307 def _readerthread(self, fh, buffer):
1308 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001309 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001310
1311
Reid Kleckner2b228f02011-03-16 16:57:54 -04001312 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001313 # Start reader threads feeding into a list hanging off of this
1314 # object, unless they've already been started.
1315 if self.stdout and not hasattr(self, "_stdout_buff"):
1316 self._stdout_buff = []
1317 self.stdout_thread = \
1318 threading.Thread(target=self._readerthread,
1319 args=(self.stdout, self._stdout_buff))
1320 self.stdout_thread.daemon = True
1321 self.stdout_thread.start()
1322 if self.stderr and not hasattr(self, "_stderr_buff"):
1323 self._stderr_buff = []
1324 self.stderr_thread = \
1325 threading.Thread(target=self._readerthread,
1326 args=(self.stderr, self._stderr_buff))
1327 self.stderr_thread.daemon = True
1328 self.stderr_thread.start()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001329
1330 if self.stdin:
Victor Stinnera5e881d2015-01-14 17:07:59 +01001331 self._stdin_write(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001332
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001333 # Wait for the reader threads, or time out. If we time out, the
1334 # threads remain reading and the fds left open in case the user
1335 # calls communicate again.
1336 if self.stdout is not None:
1337 self.stdout_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001338 if self.stdout_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001339 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001340 if self.stderr is not None:
1341 self.stderr_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001342 if self.stderr_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001343 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001344
1345 # Collect the output from and close both pipes, now that we know
1346 # both have been read successfully.
1347 stdout = None
1348 stderr = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001349 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001350 stdout = self._stdout_buff
1351 self.stdout.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001352 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001353 stderr = self._stderr_buff
1354 self.stderr.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001355
1356 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001357 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001358 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001359 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001360 stderr = stderr[0]
1361
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001362 return (stdout, stderr)
1363
Christian Heimesa342c012008-04-20 21:01:16 +00001364 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001365 """Send a signal to the process."""
1366 # Don't signal a process that we know has already died.
1367 if self.returncode is not None:
1368 return
Christian Heimesa342c012008-04-20 21:01:16 +00001369 if sig == signal.SIGTERM:
1370 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001371 elif sig == signal.CTRL_C_EVENT:
1372 os.kill(self.pid, signal.CTRL_C_EVENT)
1373 elif sig == signal.CTRL_BREAK_EVENT:
1374 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001375 else:
Brian Curtin19651362010-09-07 13:24:38 +00001376 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001377
1378 def terminate(self):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001379 """Terminates the process."""
1380 # Don't terminate a process that we know has already died.
1381 if self.returncode is not None:
1382 return
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001383 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001384 _winapi.TerminateProcess(self._handle, 1)
Antoine Pitroub69ef162012-03-11 19:33:29 +01001385 except PermissionError:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001386 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1387 # process already died.
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001388 rc = _winapi.GetExitCodeProcess(self._handle)
1389 if rc == _winapi.STILL_ACTIVE:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001390 raise
1391 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001392
1393 kill = terminate
1394
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001395 else:
1396 #
1397 # POSIX methods
1398 #
1399 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001400 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001401 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1402 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001403 p2cread, p2cwrite = -1, -1
1404 c2pread, c2pwrite = -1, -1
1405 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001406
Peter Astrandd38ddf42005-02-10 08:32:50 +00001407 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001408 pass
1409 elif stdin == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001410 p2cread, p2cwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001411 elif stdin == DEVNULL:
1412 p2cread = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001413 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001414 p2cread = stdin
1415 else:
1416 # Assuming file-like object
1417 p2cread = stdin.fileno()
1418
Peter Astrandd38ddf42005-02-10 08:32:50 +00001419 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001420 pass
1421 elif stdout == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001422 c2pread, c2pwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001423 elif stdout == DEVNULL:
1424 c2pwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001425 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001426 c2pwrite = stdout
1427 else:
1428 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001429 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001430
Peter Astrandd38ddf42005-02-10 08:32:50 +00001431 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001432 pass
1433 elif stderr == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001434 errread, errwrite = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001435 elif stderr == STDOUT:
Martin Panterc7635892016-05-13 01:54:44 +00001436 if c2pwrite != -1:
1437 errwrite = c2pwrite
1438 else: # child's stdout is not set, use parent's stdout
1439 errwrite = sys.__stdout__.fileno()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001440 elif stderr == DEVNULL:
1441 errwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001442 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001443 errwrite = stderr
1444 else:
1445 # Assuming file-like object
1446 errwrite = stderr.fileno()
1447
1448 return (p2cread, p2cwrite,
1449 c2pread, c2pwrite,
1450 errread, errwrite)
1451
1452
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001453 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001454 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001455 startupinfo, creationflags, shell,
1456 p2cread, p2cwrite,
1457 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001458 errread, errwrite,
1459 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001460 """Execute program (POSIX version)"""
1461
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001462 if isinstance(args, (str, bytes)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001463 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001464 else:
1465 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001466
1467 if shell:
1468 args = ["/bin/sh", "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001469 if executable:
1470 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001471
Peter Astrandd38ddf42005-02-10 08:32:50 +00001472 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001473 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001474 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001475
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001476 # For transferring possible exec failure from child to parent.
1477 # Data format: "exception name:hex errno:description"
1478 # Pickle is not used; it is complex and involves memory allocation.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001479 errpipe_read, errpipe_write = os.pipe()
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001480 # errpipe_write must not be in the standard io 0, 1, or 2 fd range.
1481 low_fds_to_close = []
1482 while errpipe_write < 3:
1483 low_fds_to_close.append(errpipe_write)
1484 errpipe_write = os.dup(errpipe_write)
1485 for low_fd in low_fds_to_close:
1486 os.close(low_fd)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001487 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001488 try:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001489 # We must avoid complex work that could involve
1490 # malloc or free in the child process to avoid
1491 # potential deadlocks, thus we do all this here.
1492 # and pass it to fork_exec()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001493
Victor Stinner372b8382011-06-21 17:24:21 +02001494 if env is not None:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001495 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
1496 for k, v in env.items()]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001497 else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001498 env_list = None # Use execv instead of execve.
1499 executable = os.fsencode(executable)
1500 if os.path.dirname(executable):
1501 executable_list = (executable,)
1502 else:
1503 # This matches the behavior of os._execvpe().
1504 executable_list = tuple(
1505 os.path.join(os.fsencode(dir), executable)
1506 for dir in os.get_exec_path(env))
Gregory P. Smith361e30c2013-12-01 00:12:24 -08001507 fds_to_keep = set(pass_fds)
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001508 fds_to_keep.add(errpipe_write)
1509 self.pid = _posixsubprocess.fork_exec(
1510 args, executable_list,
1511 close_fds, sorted(fds_to_keep), cwd, env_list,
1512 p2cread, p2cwrite, c2pread, c2pwrite,
1513 errread, errwrite,
1514 errpipe_read, errpipe_write,
1515 restore_signals, start_new_session, preexec_fn)
Charles-François Natali558639f2011-08-18 19:11:29 +02001516 self._child_created = True
Facundo Batista10706e22009-06-19 20:34:30 +00001517 finally:
1518 # be sure the FD is closed no matter what
1519 os.close(errpipe_write)
1520
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001521 # self._devnull is not always defined.
1522 devnull_fd = getattr(self, '_devnull', None)
1523 if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001524 os.close(p2cread)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001525 if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001526 os.close(c2pwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001527 if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001528 os.close(errwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001529 if devnull_fd is not None:
1530 os.close(devnull_fd)
1531 # Prevent a double close of these fds from __init__ on error.
1532 self._closed_child_pipe_fds = True
Facundo Batista10706e22009-06-19 20:34:30 +00001533
1534 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001535 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001536 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001537 while True:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001538 part = os.read(errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001539 errpipe_data += part
1540 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001541 break
Facundo Batista10706e22009-06-19 20:34:30 +00001542 finally:
1543 # be sure the FD is closed no matter what
1544 os.close(errpipe_read)
1545
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001546 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001547 try:
Victor Stinnera58e2c52016-05-20 12:08:12 +02001548 pid, sts = os.waitpid(self.pid, 0)
1549 if pid == self.pid:
1550 self._handle_exitstatus(sts)
1551 else:
1552 self.returncode = sys.maxsize
Victor Stinnera5e881d2015-01-14 17:07:59 +01001553 except ChildProcessError:
1554 pass
Victor Stinnera58e2c52016-05-20 12:08:12 +02001555
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001556 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001557 exception_name, hex_errno, err_msg = (
1558 errpipe_data.split(b':', 2))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001559 except ValueError:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001560 exception_name = b'SubprocessError'
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001561 hex_errno = b'0'
Gregory P. Smith3aee2222012-11-11 00:04:13 -08001562 err_msg = (b'Bad exception data from child: ' +
1563 repr(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001564 child_exception_type = getattr(
1565 builtins, exception_name.decode('ascii'),
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001566 SubprocessError)
Victor Stinner4d078042010-04-23 19:28:32 +00001567 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001568 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001569 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001570 child_exec_never_called = (err_msg == "noexec")
1571 if child_exec_never_called:
1572 err_msg = ""
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001573 if errno_num != 0:
1574 err_msg = os.strerror(errno_num)
1575 if errno_num == errno.ENOENT:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001576 if child_exec_never_called:
1577 # The error must be from chdir(cwd).
1578 err_msg += ': ' + repr(cwd)
1579 else:
1580 err_msg += ': ' + repr(orig_executable)
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001581 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001582 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001583
1584
Brett Cannon84df1e62010-05-14 00:33:40 +00001585 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1586 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1587 _WEXITSTATUS=os.WEXITSTATUS):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001588 """All callers to this function MUST hold self._waitpid_lock."""
Brett Cannon84df1e62010-05-14 00:33:40 +00001589 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka72e77612014-02-10 19:20:22 +02001590 # refer to anything outside of its local scope.
Brett Cannon84df1e62010-05-14 00:33:40 +00001591 if _WIFSIGNALED(sts):
1592 self.returncode = -_WTERMSIG(sts)
1593 elif _WIFEXITED(sts):
1594 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001595 else:
1596 # Should never happen
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001597 raise SubprocessError("Unknown child exit status!")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001598
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001599
Brett Cannon84df1e62010-05-14 00:33:40 +00001600 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov1d960fe2012-12-24 20:08:53 +02001601 _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001602 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001603 attribute.
1604
1605 This method is called by __del__, so it cannot reference anything
1606 outside of the local scope (nor can any methods it calls).
1607
1608 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001609 if self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001610 if not self._waitpid_lock.acquire(False):
1611 # Something else is busy calling waitpid. Don't allow two
1612 # at once. We know nothing yet.
1613 return None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001614 try:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001615 if self.returncode is not None:
1616 return self.returncode # Another thread waited.
Brett Cannon84df1e62010-05-14 00:33:40 +00001617 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001618 if pid == self.pid:
1619 self._handle_exitstatus(sts)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001620 except OSError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001621 if _deadstate is not None:
1622 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001623 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001624 # This happens if SIGCLD is set to be ignored or
1625 # waiting for child processes has otherwise been
1626 # disabled for our process. This child is dead, we
1627 # can't get the status.
1628 # http://bugs.python.org/issue15756
1629 self.returncode = 0
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001630 finally:
1631 self._waitpid_lock.release()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001632 return self.returncode
1633
1634
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001635 def _try_wait(self, wait_flags):
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001636 """All callers to this function MUST hold self._waitpid_lock."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001637 try:
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001638 (pid, sts) = os.waitpid(self.pid, wait_flags)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001639 except ChildProcessError:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001640 # This happens if SIGCLD is set to be ignored or waiting
1641 # for child processes has otherwise been disabled for our
1642 # process. This child is dead, we can't get the status.
1643 pid = self.pid
1644 sts = 0
1645 return (pid, sts)
1646
1647
1648 def wait(self, timeout=None, endtime=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001649 """Wait for child process to terminate. Returns returncode
1650 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001651 if self.returncode is not None:
1652 return self.returncode
Reid Kleckner2b228f02011-03-16 16:57:54 -04001653
1654 # endtime is preferred to timeout. timeout is only used for
1655 # printing.
1656 if endtime is not None or timeout is not None:
1657 if endtime is None:
Victor Stinner949d8c92012-05-30 13:30:32 +02001658 endtime = _time() + timeout
Reid Kleckner2b228f02011-03-16 16:57:54 -04001659 elif timeout is None:
1660 timeout = self._remaining_time(endtime)
1661
1662 if endtime is not None:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001663 # Enter a busy loop if we have a timeout. This busy loop was
1664 # cribbed from Lib/threading.py in Thread.wait() at r71065.
1665 delay = 0.0005 # 500 us -> initial delay of 1 ms
1666 while True:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001667 if self._waitpid_lock.acquire(False):
1668 try:
1669 if self.returncode is not None:
1670 break # Another thread waited.
1671 (pid, sts) = self._try_wait(os.WNOHANG)
1672 assert pid == self.pid or pid == 0
1673 if pid == self.pid:
1674 self._handle_exitstatus(sts)
1675 break
1676 finally:
1677 self._waitpid_lock.release()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001678 remaining = self._remaining_time(endtime)
1679 if remaining <= 0:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001680 raise TimeoutExpired(self.args, timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001681 delay = min(delay * 2, remaining, .05)
1682 time.sleep(delay)
Gregory P. Smithf328d792012-11-10 21:06:18 -08001683 else:
1684 while self.returncode is None:
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001685 with self._waitpid_lock:
1686 if self.returncode is not None:
1687 break # Another thread waited.
1688 (pid, sts) = self._try_wait(0)
1689 # Check the pid and loop as waitpid has been known to
1690 # return 0 even without WNOHANG in odd situations.
1691 # http://bugs.python.org/issue14396.
1692 if pid == self.pid:
1693 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001694 return self.returncode
1695
1696
Reid Kleckner2b228f02011-03-16 16:57:54 -04001697 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001698 if self.stdin and not self._communication_started:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001699 # Flush stdio buffer. This might block, if the user has
1700 # been writing to .stdin in an uncontrolled fashion.
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001701 try:
1702 self.stdin.flush()
1703 except BrokenPipeError:
1704 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001705 if not input:
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00001706 try:
1707 self.stdin.close()
1708 except BrokenPipeError:
1709 pass # communicate() must ignore BrokenPipeError.
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001710
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001711 stdout = None
1712 stderr = None
1713
1714 # Only create this mapping if we haven't already.
1715 if not self._communication_started:
1716 self._fileobj2output = {}
1717 if self.stdout:
1718 self._fileobj2output[self.stdout] = []
1719 if self.stderr:
1720 self._fileobj2output[self.stderr] = []
1721
1722 if self.stdout:
1723 stdout = self._fileobj2output[self.stdout]
1724 if self.stderr:
1725 stderr = self._fileobj2output[self.stderr]
1726
1727 self._save_input(input)
1728
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001729 if self._input:
1730 input_view = memoryview(self._input)
1731
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001732 with _PopenSelector() as selector:
1733 if self.stdin and input:
1734 selector.register(self.stdin, selectors.EVENT_WRITE)
1735 if self.stdout:
1736 selector.register(self.stdout, selectors.EVENT_READ)
1737 if self.stderr:
1738 selector.register(self.stderr, selectors.EVENT_READ)
1739
1740 while selector.get_map():
1741 timeout = self._remaining_time(endtime)
1742 if timeout is not None and timeout < 0:
1743 raise TimeoutExpired(self.args, orig_timeout)
1744
1745 ready = selector.select(timeout)
1746 self._check_timeout(endtime, orig_timeout)
1747
1748 # XXX Rewrite these to use non-blocking I/O on the file
1749 # objects; they are no longer using C stdio!
1750
1751 for key, events in ready:
1752 if key.fileobj is self.stdin:
Gregory P. Smith5ca129b2013-12-07 19:14:59 -08001753 chunk = input_view[self._input_offset :
1754 self._input_offset + _PIPE_BUF]
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001755 try:
1756 self._input_offset += os.write(key.fd, chunk)
Victor Stinnera5e881d2015-01-14 17:07:59 +01001757 except BrokenPipeError:
1758 selector.unregister(key.fileobj)
1759 key.fileobj.close()
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001760 else:
1761 if self._input_offset >= len(self._input):
1762 selector.unregister(key.fileobj)
1763 key.fileobj.close()
1764 elif key.fileobj in (self.stdout, self.stderr):
Gregory P. Smith7b83b182013-12-08 10:58:28 -08001765 data = os.read(key.fd, 32768)
Charles-François Natali3a4586a2013-11-08 19:56:59 +01001766 if not data:
1767 selector.unregister(key.fileobj)
1768 key.fileobj.close()
1769 self._fileobj2output[key.fileobj].append(data)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001770
1771 self.wait(timeout=self._remaining_time(endtime))
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001772
1773 # All data exchanged. Translate lists into strings.
1774 if stdout is not None:
1775 stdout = b''.join(stdout)
1776 if stderr is not None:
1777 stderr = b''.join(stderr)
1778
1779 # Translate newlines, if requested.
1780 # This also turns bytes into strings.
Steve Dower050acae2016-09-06 20:16:17 -07001781 if self.encoding or self.errors or self.universal_newlines:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001782 if stdout is not None:
1783 stdout = self._translate_newlines(stdout,
Steve Dower050acae2016-09-06 20:16:17 -07001784 self.stdout.encoding,
1785 self.stdout.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001786 if stderr is not None:
1787 stderr = self._translate_newlines(stderr,
Steve Dower050acae2016-09-06 20:16:17 -07001788 self.stderr.encoding,
1789 self.stderr.errors)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001790
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001791 return (stdout, stderr)
1792
1793
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001794 def _save_input(self, input):
1795 # This method is called from the _communicate_with_*() methods
1796 # so that if we time out while communicating, we can continue
1797 # sending input if we retry.
1798 if self.stdin and self._input is None:
1799 self._input_offset = 0
1800 self._input = input
Steve Dower050acae2016-09-06 20:16:17 -07001801 if input is not None and (
1802 self.encoding or self.errors or self.universal_newlines):
1803 self._input = self._input.encode(self.stdin.encoding,
1804 self.stdin.errors)
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001805
1806
Christian Heimesa342c012008-04-20 21:01:16 +00001807 def send_signal(self, sig):
Gregory P. Smitha0c9caa2015-11-15 18:19:10 -08001808 """Send a signal to the process."""
1809 # Skip signalling a process that we know has already died.
1810 if self.returncode is None:
1811 os.kill(self.pid, sig)
Christian Heimesa342c012008-04-20 21:01:16 +00001812
1813 def terminate(self):
1814 """Terminate the process with SIGTERM
1815 """
1816 self.send_signal(signal.SIGTERM)
1817
1818 def kill(self):
1819 """Kill the process with SIGKILL
1820 """
1821 self.send_signal(signal.SIGKILL)