blob: 1bfd136ec4b2b15c334e356650fa1e4f5c5fd6f3 [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
14intends to replace several other, older modules and functions, like:
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,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +000033 restore_signals=True, start_new_session=False, pass_fds=()):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034
35
36Arguments are:
37
38args should be a string, or a sequence of program arguments. The
39program to execute is normally the first item in the args sequence or
40string, but can be explicitly set by using the executable argument.
41
Gregory P. Smithf5604852010-12-13 06:45:02 +000042On POSIX, with shell=False (default): In this case, the Popen class
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043uses os.execvp() to execute the child program. args should normally
44be a sequence. A string will be treated as a sequence with the string
45as the only item (the program to execute).
46
Gregory P. Smithf5604852010-12-13 06:45:02 +000047On POSIX, with shell=True: If args is a string, it specifies the
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000048command string to execute through the shell. If args is a sequence,
49the first item specifies the command string, and any additional items
50will be treated as additional shell arguments.
51
52On Windows: the Popen class uses CreateProcess() to execute the child
53program, which operates on strings. If args is a sequence, it will be
54converted to a string using the list2cmdline method. Please note that
55not all MS Windows applications interpret the command line the same
56way: The list2cmdline is designed for applications using the same
57rules as the MS C runtime.
58
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070059bufsize will be supplied as the corresponding argument to the io.open()
60function when creating the stdin/stdout/stderr pipe file objects:
610 means unbuffered (read & write are one system call and can return short),
621 means line buffered, any other positive value means use a buffer of
63approximately that size. A negative bufsize, the default, means the system
64default of io.DEFAULT_BUFFER_SIZE will be used.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000065
66stdin, stdout and stderr specify the executed programs' standard
67input, standard output and standard error file handles, respectively.
68Valid values are PIPE, an existing file descriptor (a positive
69integer), an existing file object, and None. PIPE indicates that a
70new pipe to the child should be created. With None, no redirection
71will occur; the child's file handles will be inherited from the
72parent. Additionally, stderr can be STDOUT, which indicates that the
73stderr data from the applications should be captured into the same
74file handle as for stdout.
75
Gregory P. Smithf5604852010-12-13 06:45:02 +000076On POSIX, if preexec_fn is set to a callable object, this object will be
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000077called in the child process just before the child is executed. The use
78of preexec_fn is not thread safe, using it in the presence of threads
79could lead to a deadlock in the child process before the new executable
80is executed.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000081
82If close_fds is true, all file descriptors except 0, 1 and 2 will be
Gregory P. Smithf5604852010-12-13 06:45:02 +000083closed before the child process is executed. The default for close_fds
Gregory P. Smith8edd99d2010-12-14 13:43:30 +000084varies by platform: Always true on POSIX. True when stdin/stdout/stderr
85are None on Windows, false otherwise.
86
87pass_fds is an optional sequence of file descriptors to keep open between the
88parent and child. Providing any pass_fds implicitly sets close_fds to true.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000089
90if shell is true, the specified command will be executed through the
91shell.
92
93If cwd is not None, the current directory will be changed to cwd
94before the child is executed.
95
Gregory P. Smithf5604852010-12-13 06:45:02 +000096On POSIX, if restore_signals is True all signals that Python sets to
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000097SIG_IGN are restored to SIG_DFL in the child process before the exec.
98Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This
99parameter does nothing on Windows.
100
Gregory P. Smithf5604852010-12-13 06:45:02 +0000101On POSIX, if start_new_session is True, the setsid() system call will be made
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000102in the child process prior to executing the command.
103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000104If env is not None, it defines the environment variables for the new
105process.
106
Ronald Oussoren385521c2013-07-07 09:26:45 +0200107If universal_newlines is false, the file objects stdin, stdout and stderr
108are opened as binary files, and no line ending conversion is done.
109
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110If universal_newlines is true, the file objects stdout and stderr are
111opened as a text files, but lines may be terminated by any of '\n',
Gregory P. Smithf5604852010-12-13 06:45:02 +0000112the Unix end-of-line convention, '\r', the old Macintosh convention or
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113'\r\n', the Windows convention. All of these external representations
Gregory P. Smith1f8a40b2013-03-20 18:32:03 -0700114are seen as '\n' by the Python program. Also, the newlines attribute
115of the file objects stdout, stdin and stderr are not updated by the
116communicate() method.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000117
118The startupinfo and creationflags, if given, will be passed to the
119underlying CreateProcess() function. They can specify things such as
120appearance of the main window and priority for the new process.
121(Windows only)
122
123
Georg Brandlf9734072008-12-07 15:30:06 +0000124This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125
Peter Astrand5f5e1412004-12-05 20:15:36 +0000126call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127 Run command with arguments. Wait for command to complete, then
128 return the returncode attribute.
129
130 The arguments are the same as for the Popen constructor. Example:
131
Florent Xicluna4886d242010-03-08 13:27:26 +0000132 >>> retcode = subprocess.call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000133
Peter Astrand454f7672005-01-01 09:36:35 +0000134check_call(*popenargs, **kwargs):
135 Run command with arguments. Wait for command to complete. If the
136 exit code was zero then return, otherwise raise
137 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000139
140 The arguments are the same as for the Popen constructor. Example:
141
Florent Xicluna4886d242010-03-08 13:27:26 +0000142 >>> subprocess.check_call(["ls", "-l"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000143 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144
Brett Cannona23810f2008-05-26 19:04:21 +0000145getstatusoutput(cmd):
146 Return (status, output) of executing cmd in a shell.
147
148 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
149 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
150 returned output will contain output or error messages. A trailing newline
151 is stripped from the output. The exit status for the command can be
152 interpreted according to the rules for the C function wait(). Example:
153
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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185Exceptions
186----------
187Exceptions raised in the child process, before the new program has
188started to execute, will be re-raised in the parent. Additionally,
189the exception object will have one extra attribute called
190'child_traceback', which is a string containing traceback information
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300191from the child's point of view.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192
193The most common exception raised is OSError. This occurs, for
194example, when trying to execute a non-existent file. Applications
195should prepare for OSErrors.
196
197A ValueError will be raised if Popen is called with invalid arguments.
198
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400199Exceptions defined within this module inherit from SubprocessError.
200check_call() and check_output() will raise CalledProcessError if the
Gregory P. Smithb4039aa2011-03-14 14:16:20 -0400201called process returns a non-zero return code. TimeoutExpired
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400202be raised if a timeout was specified and expired.
Peter Astrand454f7672005-01-01 09:36:35 +0000203
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204
205Security
206--------
207Unlike some other popen functions, this implementation will never call
208/bin/sh implicitly. This means that all characters, including shell
209metacharacters, can safely be passed to child processes.
210
211
212Popen objects
213=============
214Instances of the Popen class have the following methods:
215
216poll()
217 Check if child process has terminated. Returns returncode
218 attribute.
219
220wait()
221 Wait for child process to terminate. Returns returncode attribute.
222
223communicate(input=None)
224 Interact with process: Send data to stdin. Read data from stdout
225 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000226 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 sent to the child process, or None, if no data should be sent to
228 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000229
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 communicate() returns a tuple (stdout, stderr).
231
232 Note: The data read is buffered in memory, so do not use this
233 method if the data size is large or unlimited.
234
235The following attributes are also available:
236
237stdin
238 If the stdin argument is PIPE, this attribute is a file object
239 that provides input to the child process. Otherwise, it is None.
240
241stdout
242 If the stdout argument is PIPE, this attribute is a file object
243 that provides output from the child process. Otherwise, it is
244 None.
245
246stderr
247 If the stderr argument is PIPE, this attribute is file object that
248 provides error output from the child process. Otherwise, it is
249 None.
250
251pid
252 The process ID of the child process.
253
254returncode
255 The child return code. A None value indicates that the process
256 hasn't terminated yet. A negative value -N indicates that the
Gregory P. Smithf5604852010-12-13 06:45:02 +0000257 child was terminated by signal N (POSIX only).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259
260Replacing older functions with the subprocess module
261====================================================
262In this section, "a ==> b" means that b can be used as a replacement
263for a.
264
265Note: All functions in this section fail (more or less) silently if
266the executed program cannot be found; this module raises an OSError
267exception.
268
269In the following examples, we assume that the subprocess module is
270imported with "from subprocess import *".
271
272
273Replacing /bin/sh shell backquote
274---------------------------------
275output=`mycmd myarg`
276==>
277output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
278
279
280Replacing shell pipe line
281-------------------------
282output=`dmesg | grep hda`
283==>
284p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000285p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286output = p2.communicate()[0]
287
288
289Replacing os.system()
290---------------------
291sts = os.system("mycmd" + " myarg")
292==>
293p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295
296Note:
297
298* Calling the program through the shell is usually not required.
299
300* It's easier to look at the returncode attribute than the
301 exitstatus.
302
303A more real-world example would look like this:
304
305try:
306 retcode = call("mycmd" + " myarg", shell=True)
307 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000308 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000310 print("Child returned", retcode, file=sys.stderr)
311except OSError as e:
312 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313
314
315Replacing os.spawn*
316-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000317P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318
319pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
320==>
321pid = Popen(["/bin/mycmd", "myarg"]).pid
322
323
324P_WAIT example:
325
326retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
327==>
328retcode = call(["/bin/mycmd", "myarg"])
329
330
Tim Peterse718f612004-10-12 21:51:32 +0000331Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
333os.spawnvp(os.P_NOWAIT, path, args)
334==>
335Popen([path] + args[1:])
336
337
Tim Peterse718f612004-10-12 21:51:32 +0000338Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339
340os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
341==>
342Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343"""
344
345import sys
346mswindows = (sys.platform == "win32")
347
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000348import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349import os
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400350import time
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000351import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000352import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000353import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000354import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000355import warnings
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200356import errno
Victor Stinner949d8c92012-05-30 13:30:32 +0200357try:
358 from time import monotonic as _time
Brett Cannoncd171c82013-07-04 17:43:24 -0400359except ImportError:
Victor Stinner949d8c92012-05-30 13:30:32 +0200360 from time import time as _time
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361
Peter Astrand454f7672005-01-01 09:36:35 +0000362# Exception classes used by this module.
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400363class SubprocessError(Exception): pass
364
365
366class CalledProcessError(SubprocessError):
Georg Brandlf9734072008-12-07 15:30:06 +0000367 """This exception is raised when a process run by check_call() or
368 check_output() returns a non-zero exit status.
369 The exit status will be stored in the returncode attribute;
370 check_output() will also store the output in the output attribute.
371 """
372 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000373 self.returncode = returncode
374 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000375 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000376 def __str__(self):
377 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
378
Peter Astrand454f7672005-01-01 09:36:35 +0000379
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400380class TimeoutExpired(SubprocessError):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400381 """This exception is raised when the timeout expires while waiting for a
382 child process.
383 """
Reid Kleckner2b228f02011-03-16 16:57:54 -0400384 def __init__(self, cmd, timeout, output=None):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400385 self.cmd = cmd
Reid Kleckner2b228f02011-03-16 16:57:54 -0400386 self.timeout = timeout
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400387 self.output = output
388
389 def __str__(self):
390 return ("Command '%s' timed out after %s seconds" %
391 (self.cmd, self.timeout))
392
393
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394if mswindows:
395 import threading
396 import msvcrt
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200397 import _winapi
Brian Curtin1ce6b582010-04-24 16:19:22 +0000398 class STARTUPINFO:
399 dwFlags = 0
400 hStdInput = None
401 hStdOutput = None
402 hStdError = None
403 wShowWindow = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404else:
405 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000406 _has_poll = hasattr(select, 'poll')
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -0700407 import _posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000408
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000409 # When select or poll has indicated that the file is writable,
410 # we can write up to _PIPE_BUF bytes without risk of blocking.
411 # POSIX defines PIPE_BUF as >= 512.
412 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
413
414
Brett Cannona23810f2008-05-26 19:04:21 +0000415__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200416 "getoutput", "check_output", "CalledProcessError", "DEVNULL"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417
Brian Curtin1ce6b582010-04-24 16:19:22 +0000418if mswindows:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200419 from _winapi import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
420 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
421 STD_ERROR_HANDLE, SW_HIDE,
422 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Brian Curtin5d9deaa2011-04-29 16:24:07 -0500423
Brian Curtin08fd8d92011-04-29 16:11:30 -0500424 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500425 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
426 "STD_ERROR_HANDLE", "SW_HIDE",
427 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200428
429 class Handle(int):
430 closed = False
431
432 def Close(self, CloseHandle=_winapi.CloseHandle):
433 if not self.closed:
434 self.closed = True
435 CloseHandle(self)
436
437 def Detach(self):
438 if not self.closed:
439 self.closed = True
440 return int(self)
441 raise ValueError("already closed")
442
443 def __repr__(self):
444 return "Handle(%d)" % int(self)
445
446 __del__ = Close
447 __str__ = __repr__
448
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449try:
450 MAXFD = os.sysconf("SC_OPEN_MAX")
451except:
452 MAXFD = 256
453
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200454# This lists holds Popen instances for which the underlying process had not
455# exited at the time its __del__ method got called: those processes are wait()ed
456# for synchronously from _cleanup() when a new Popen object is created, to avoid
457# zombie processes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458_active = []
459
460def _cleanup():
461 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000462 res = inst._internal_poll(_deadstate=sys.maxsize)
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200463 if res is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 try:
465 _active.remove(inst)
466 except ValueError:
467 # This can happen if two threads create a new Popen instance.
468 # It's harmless that it was already removed, so ignore.
469 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470
471PIPE = -1
472STDOUT = -2
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200473DEVNULL = -3
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474
475
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000476def _eintr_retry_call(func, *args):
477 while True:
478 try:
479 return func(*args)
Antoine Pitrou24d659d2011-10-23 23:49:42 +0200480 except InterruptedError:
481 continue
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000482
483
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200484# XXX This function is only used by multiprocessing and the test suite,
485# but it's here so that it can be imported when Python is compiled without
486# threads.
487
488def _args_from_interpreter_flags():
489 """Return a list of command-line arguments reproducing the current
490 settings in sys.flags and sys.warnoptions."""
491 flag_opt_map = {
492 'debug': 'd',
493 # 'inspect': 'i',
494 # 'interactive': 'i',
495 'optimize': 'O',
496 'dont_write_bytecode': 'B',
497 'no_user_site': 's',
498 'no_site': 'S',
499 'ignore_environment': 'E',
500 'verbose': 'v',
501 'bytes_warning': 'b',
502 'quiet': 'q',
503 'hash_randomization': 'R',
504 }
505 args = []
506 for flag, opt in flag_opt_map.items():
507 v = getattr(sys.flags, flag)
508 if v > 0:
Nick Coghlanac1a2482013-10-18 22:39:50 +1000509 if flag == 'hash_randomization':
510 v = 1 # Handle specification of an exact seed
Antoine Pitrouebdcd852012-05-18 18:33:07 +0200511 args.append('-' + opt * v)
512 for opt in sys.warnoptions:
513 args.append('-W' + opt)
514 return args
515
516
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400517def call(*popenargs, timeout=None, **kwargs):
518 """Run command with arguments. Wait for command to complete or
519 timeout, then return the returncode attribute.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
521 The arguments are the same as for the Popen constructor. Example:
522
523 retcode = call(["ls", "-l"])
524 """
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200525 with Popen(*popenargs, **kwargs) as p:
526 try:
527 return p.wait(timeout=timeout)
528 except:
529 p.kill()
530 p.wait()
531 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532
533
Peter Astrand454f7672005-01-01 09:36:35 +0000534def check_call(*popenargs, **kwargs):
535 """Run command with arguments. Wait for command to complete. If
536 the exit code was zero then return, otherwise raise
537 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000538 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000539
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400540 The arguments are the same as for the call function. Example:
Peter Astrand454f7672005-01-01 09:36:35 +0000541
542 check_call(["ls", "-l"])
543 """
544 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000545 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000546 cmd = kwargs.get("args")
547 if cmd is None:
548 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000549 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000550 return 0
551
552
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400553def check_output(*popenargs, timeout=None, **kwargs):
Gregory P. Smith91110f52013-03-19 23:25:16 -0700554 r"""Run command with arguments and return its output.
Georg Brandlf9734072008-12-07 15:30:06 +0000555
556 If the exit code was non-zero it raises a CalledProcessError. The
557 CalledProcessError object will have the return code in the returncode
558 attribute and output in the output attribute.
559
560 The arguments are the same as for the Popen constructor. Example:
561
562 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000563 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000564
565 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000566 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000567
568 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000569 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000570 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000571 b'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith91110f52013-03-19 23:25:16 -0700572
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300573 There is an additional optional argument, "input", allowing you to
574 pass a string to the subprocess's stdin. If you use this argument
575 you may not also use the Popen constructor's "stdin" argument, as
576 it too will be used internally. Example:
577
578 >>> check_output(["sed", "-e", "s/foo/bar/"],
579 ... input=b"when in the course of fooman events\n")
580 b'when in the course of barman events\n'
581
Gregory P. Smith91110f52013-03-19 23:25:16 -0700582 If universal_newlines=True is passed, the return value will be a
583 string rather than bytes.
Georg Brandlf9734072008-12-07 15:30:06 +0000584 """
585 if 'stdout' in kwargs:
586 raise ValueError('stdout argument not allowed, it will be overridden.')
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300587 if 'input' in kwargs:
588 if 'stdin' in kwargs:
589 raise ValueError('stdin and input arguments may not both be used.')
590 inputdata = kwargs['input']
591 del kwargs['input']
592 kwargs['stdin'] = PIPE
593 else:
594 inputdata = None
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200595 with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
596 try:
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300597 output, unused_err = process.communicate(inputdata, timeout=timeout)
Victor Stinnerc15c88c2011-09-01 23:45:04 +0200598 except TimeoutExpired:
599 process.kill()
600 output, unused_err = process.communicate()
601 raise TimeoutExpired(process.args, timeout, output=output)
602 except:
603 process.kill()
604 process.wait()
605 raise
606 retcode = process.poll()
607 if retcode:
608 raise CalledProcessError(retcode, process.args, output=output)
Georg Brandlf9734072008-12-07 15:30:06 +0000609 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000610
611
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612def list2cmdline(seq):
613 """
614 Translate a sequence of arguments into a command line
615 string, using the same rules as the MS C runtime:
616
617 1) Arguments are delimited by white space, which is either a
618 space or a tab.
619
620 2) A string surrounded by double quotation marks is
621 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000622 contained within. A quoted string can be embedded in an
623 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624
625 3) A double quotation mark preceded by a backslash is
626 interpreted as a literal double quotation mark.
627
628 4) Backslashes are interpreted literally, unless they
629 immediately precede a double quotation mark.
630
631 5) If backslashes immediately precede a double quotation mark,
632 every pair of backslashes is interpreted as a literal
633 backslash. If the number of backslashes is odd, the last
634 backslash escapes the next double quotation mark as
635 described in rule 3.
636 """
637
638 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000639 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
640 # or search http://msdn.microsoft.com for
641 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 result = []
643 needquote = False
644 for arg in seq:
645 bs_buf = []
646
647 # Add a space to separate this argument from the others
648 if result:
649 result.append(' ')
650
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000651 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 if needquote:
653 result.append('"')
654
655 for c in arg:
656 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000657 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 bs_buf.append(c)
659 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000660 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 result.append('\\' * len(bs_buf)*2)
662 bs_buf = []
663 result.append('\\"')
664 else:
665 # Normal char
666 if bs_buf:
667 result.extend(bs_buf)
668 bs_buf = []
669 result.append(c)
670
Christian Heimesfdab48e2008-01-20 09:06:41 +0000671 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 if bs_buf:
673 result.extend(bs_buf)
674
675 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000676 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000677 result.append('"')
678
679 return ''.join(result)
680
681
Brett Cannona23810f2008-05-26 19:04:21 +0000682# Various tools for executing commands and looking at their output and status.
683#
Gregory P. Smithf5604852010-12-13 06:45:02 +0000684# NB This only works (and is only relevant) for POSIX.
Brett Cannona23810f2008-05-26 19:04:21 +0000685
686def getstatusoutput(cmd):
687 """Return (status, output) of executing cmd in a shell.
688
689 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
690 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
691 returned output will contain output or error messages. A trailing newline
692 is stripped from the output. The exit status for the command can be
693 interpreted according to the rules for the C function wait(). Example:
694
695 >>> import subprocess
696 >>> subprocess.getstatusoutput('ls /bin/ls')
697 (0, '/bin/ls')
698 >>> subprocess.getstatusoutput('cat /bin/junk')
699 (256, 'cat: /bin/junk: No such file or directory')
700 >>> subprocess.getstatusoutput('/bin/junk')
701 (256, 'sh: /bin/junk: not found')
702 """
Tim Goldene0041752013-11-03 12:53:17 +0000703 try:
704 data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
705 status = 0
706 except CalledProcessError as ex:
707 data = ex.output
708 status = ex.returncode
709 if data[-1:] == '\n':
710 data = data[:-1]
711 return status, data
Brett Cannona23810f2008-05-26 19:04:21 +0000712
713def getoutput(cmd):
714 """Return output (stdout or stderr) of executing cmd in a shell.
715
716 Like getstatusoutput(), except the exit status is ignored and the return
717 value is a string containing the command's output. Example:
718
719 >>> import subprocess
720 >>> subprocess.getoutput('ls /bin/ls')
721 '/bin/ls'
722 """
723 return getstatusoutput(cmd)[1]
724
725
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000726_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000727
728
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729class Popen(object):
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700730 def __init__(self, args, bufsize=-1, executable=None,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000732 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
733 shell=False, cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000734 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000735 restore_signals=True, start_new_session=False,
736 pass_fds=()):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737 """Create new Popen instance."""
738 _cleanup()
739
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000740 self._child_created = False
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400741 self._input = None
742 self._communication_started = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000743 if bufsize is None:
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700744 bufsize = -1 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000745 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000746 raise TypeError("bufsize must be an integer")
747
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000749 if preexec_fn is not None:
750 raise ValueError("preexec_fn is not supported on Windows "
751 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000752 any_stdio_set = (stdin is not None or stdout is not None or
753 stderr is not None)
754 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
755 if any_stdio_set:
756 close_fds = False
757 else:
758 close_fds = True
759 elif close_fds and any_stdio_set:
760 raise ValueError(
761 "close_fds is not supported on Windows platforms"
762 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000763 else:
764 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000765 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
766 close_fds = True
767 if pass_fds and not close_fds:
768 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
769 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000770 if startupinfo is not None:
771 raise ValueError("startupinfo is only supported on Windows "
772 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000774 raise ValueError("creationflags is only supported on Windows "
775 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000776
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400777 self.args = args
Tim Peterse718f612004-10-12 21:51:32 +0000778 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779 self.stdout = None
780 self.stderr = None
781 self.pid = None
782 self.returncode = None
783 self.universal_newlines = universal_newlines
784
785 # Input and output objects. The general principle is like
786 # this:
787 #
788 # Parent Child
789 # ------ -----
790 # p2cwrite ---stdin---> p2cread
791 # c2pread <--stdout--- c2pwrite
792 # errread <--stderr--- errwrite
793 #
794 # On POSIX, the child objects are file descriptors. On
795 # Windows, these are Windows file handles. The parent objects
796 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000797 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000799
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 (p2cread, p2cwrite,
801 c2pread, c2pwrite,
802 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
803
Antoine Pitrouc9982322011-01-04 19:07:07 +0000804 # We wrap OS handles *before* launching the child, otherwise a
805 # quickly terminating child could make our fds unwrappable
806 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807
Thomas Wouterscf297e42007-02-23 15:07:44 +0000808 if mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000809 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000810 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000811 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000812 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000813 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000814 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000815
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000816 if p2cwrite != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000817 self.stdin = io.open(p2cwrite, 'wb', bufsize)
Andrew Svetlov592df202012-08-15 17:36:15 +0300818 if universal_newlines:
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200819 self.stdin = io.TextIOWrapper(self.stdin, write_through=True)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000820 if c2pread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000821 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000822 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000823 self.stdout = io.TextIOWrapper(self.stdout)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000824 if errread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000825 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000827 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000828
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700829 self._closed_child_pipe_fds = False
Antoine Pitrouc9982322011-01-04 19:07:07 +0000830 try:
831 self._execute_child(args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +0300832 pass_fds, cwd, env,
Antoine Pitrouc9982322011-01-04 19:07:07 +0000833 startupinfo, creationflags, shell,
834 p2cread, p2cwrite,
835 c2pread, c2pwrite,
836 errread, errwrite,
837 restore_signals, start_new_session)
838 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800839 # Cleanup if the child failed starting.
840 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000841 try:
842 f.close()
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200843 except OSError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800844 pass # Ignore EBADF or other errors.
845
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700846 if not self._closed_child_pipe_fds:
847 to_close = []
848 if stdin == PIPE:
849 to_close.append(p2cread)
850 if stdout == PIPE:
851 to_close.append(c2pwrite)
852 if stderr == PIPE:
853 to_close.append(errwrite)
854 if hasattr(self, '_devnull'):
855 to_close.append(self._devnull)
856 for fd in to_close:
857 try:
858 os.close(fd)
Gregory P. Smith22ba31a2013-06-15 18:14:56 -0700859 except OSError:
Gregory P. Smithb5461b92013-06-15 18:04:26 -0700860 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800861
Antoine Pitrouc9982322011-01-04 19:07:07 +0000862 raise
863
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864
Guido van Rossum98297ee2007-11-06 21:34:58 +0000865 def _translate_newlines(self, data, encoding):
Andrew Svetlov82860712012-08-19 22:13:41 +0300866 data = data.decode(encoding)
867 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868
Brian Curtin79cdb662010-12-03 02:46:02 +0000869 def __enter__(self):
870 return self
871
872 def __exit__(self, type, value, traceback):
873 if self.stdout:
874 self.stdout.close()
875 if self.stderr:
876 self.stderr.close()
877 if self.stdin:
878 self.stdin.close()
Gregory P. Smith6b657452011-05-11 21:42:08 -0700879 # Wait for the process to terminate, to avoid zombies.
880 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000881
Brett Cannon84df1e62010-05-14 00:33:40 +0000882 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Victor Stinner87b9bc32011-06-01 00:57:47 +0200883 # If __init__ hasn't had a chance to execute (e.g. if it
884 # was passed an undeclared keyword argument), we don't
885 # have a _child_created attribute at all.
886 if not getattr(self, '_child_created', False):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000887 # We didn't get to successfully create a child process.
888 return
889 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000890 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000891 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000892 # Child is still running, keep us alive until we can wait on it.
893 _active.append(self)
894
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200895 def _get_devnull(self):
896 if not hasattr(self, '_devnull'):
897 self._devnull = os.open(os.devnull, os.O_RDWR)
898 return self._devnull
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000899
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400900 def communicate(self, input=None, timeout=None):
Peter Astrand23109f02005-03-03 20:28:59 +0000901 """Interact with process: Send data to stdin. Read data from
902 stdout and stderr, until end-of-file is reached. Wait for
Gregory P. Smitha454ef62011-05-22 22:29:49 -0700903 process to terminate. The optional input argument should be
904 bytes to be sent to the child process, or None, if no data
Peter Astrand23109f02005-03-03 20:28:59 +0000905 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000906
Peter Astrand23109f02005-03-03 20:28:59 +0000907 communicate() returns a tuple (stdout, stderr)."""
908
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400909 if self._communication_started and input:
910 raise ValueError("Cannot send input after starting communication")
911
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400912 # Optimization: If we are not worried about timeouts, we haven't
913 # started communicating, and we have one or zero pipes, using select()
914 # or threads is unnecessary.
Victor Stinner7a8d0812011-04-05 13:13:08 +0200915 if (timeout is None and not self._communication_started and
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400916 [self.stdin, self.stdout, self.stderr].count(None) >= 2):
Tim Peterseba28be2005-03-28 01:08:02 +0000917 stdout = None
918 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000919 if self.stdin:
920 if input:
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200921 try:
922 self.stdin.write(input)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200923 except OSError as e:
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200924 if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
925 raise
Peter Astrand23109f02005-03-03 20:28:59 +0000926 self.stdin.close()
927 elif self.stdout:
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200928 stdout = _eintr_retry_call(self.stdout.read)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000929 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000930 elif self.stderr:
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200931 stderr = _eintr_retry_call(self.stderr.read)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000932 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000933 self.wait()
Victor Stinner7a8d0812011-04-05 13:13:08 +0200934 else:
935 if timeout is not None:
Victor Stinner949d8c92012-05-30 13:30:32 +0200936 endtime = _time() + timeout
Victor Stinner7a8d0812011-04-05 13:13:08 +0200937 else:
938 endtime = None
Tim Peterseba28be2005-03-28 01:08:02 +0000939
Victor Stinner7a8d0812011-04-05 13:13:08 +0200940 try:
941 stdout, stderr = self._communicate(input, endtime, timeout)
942 finally:
943 self._communication_started = True
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400944
Victor Stinner7a8d0812011-04-05 13:13:08 +0200945 sts = self.wait(timeout=self._remaining_time(endtime))
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400946
947 return (stdout, stderr)
Peter Astrand23109f02005-03-03 20:28:59 +0000948
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000950 def poll(self):
951 return self._internal_poll()
952
953
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400954 def _remaining_time(self, endtime):
955 """Convenience for _communicate when computing timeouts."""
956 if endtime is None:
957 return None
958 else:
Victor Stinner949d8c92012-05-30 13:30:32 +0200959 return endtime - _time()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400960
961
Reid Kleckner2b228f02011-03-16 16:57:54 -0400962 def _check_timeout(self, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400963 """Convenience for checking if a timeout has expired."""
964 if endtime is None:
965 return
Victor Stinner949d8c92012-05-30 13:30:32 +0200966 if _time() > endtime:
Reid Kleckner2b228f02011-03-16 16:57:54 -0400967 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400968
969
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970 if mswindows:
971 #
972 # Windows methods
973 #
974 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000975 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
977 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000978 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000979 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000980
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000981 p2cread, p2cwrite = -1, -1
982 c2pread, c2pwrite = -1, -1
983 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984
Peter Astrandd38ddf42005-02-10 08:32:50 +0000985 if stdin is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200986 p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000987 if p2cread is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200988 p2cread, _ = _winapi.CreatePipe(None, 0)
989 p2cread = Handle(p2cread)
990 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000991 elif stdin == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200992 p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
993 p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200994 elif stdin == DEVNULL:
995 p2cread = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +0000996 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 p2cread = msvcrt.get_osfhandle(stdin)
998 else:
999 # Assuming file-like object
1000 p2cread = msvcrt.get_osfhandle(stdin.fileno())
1001 p2cread = self._make_inheritable(p2cread)
1002
Peter Astrandd38ddf42005-02-10 08:32:50 +00001003 if stdout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001004 c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001005 if c2pwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001006 _, c2pwrite = _winapi.CreatePipe(None, 0)
1007 c2pwrite = Handle(c2pwrite)
1008 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001009 elif stdout == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001010 c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
1011 c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001012 elif stdout == DEVNULL:
1013 c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001014 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001015 c2pwrite = msvcrt.get_osfhandle(stdout)
1016 else:
1017 # Assuming file-like object
1018 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
1019 c2pwrite = self._make_inheritable(c2pwrite)
1020
Peter Astrandd38ddf42005-02-10 08:32:50 +00001021 if stderr is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001022 errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001023 if errwrite is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001024 _, errwrite = _winapi.CreatePipe(None, 0)
1025 errwrite = Handle(errwrite)
1026 _winapi.CloseHandle(_)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +00001027 elif stderr == PIPE:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001028 errread, errwrite = _winapi.CreatePipe(None, 0)
1029 errread, errwrite = Handle(errread), Handle(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 elif stderr == STDOUT:
1031 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001032 elif stderr == DEVNULL:
1033 errwrite = msvcrt.get_osfhandle(self._get_devnull())
Peter Astrandd38ddf42005-02-10 08:32:50 +00001034 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001035 errwrite = msvcrt.get_osfhandle(stderr)
1036 else:
1037 # Assuming file-like object
1038 errwrite = msvcrt.get_osfhandle(stderr.fileno())
1039 errwrite = self._make_inheritable(errwrite)
1040
1041 return (p2cread, p2cwrite,
1042 c2pread, c2pwrite,
1043 errread, errwrite)
1044
1045
1046 def _make_inheritable(self, handle):
1047 """Return a duplicate of handle, which is inheritable"""
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001048 h = _winapi.DuplicateHandle(
1049 _winapi.GetCurrentProcess(), handle,
1050 _winapi.GetCurrentProcess(), 0, 1,
1051 _winapi.DUPLICATE_SAME_ACCESS)
1052 return Handle(h)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053
1054
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001056 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057 startupinfo, creationflags, shell,
1058 p2cread, p2cwrite,
1059 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001060 errread, errwrite,
1061 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001062 """Execute program (MS Windows version)"""
1063
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001064 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001065
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001066 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067 args = list2cmdline(args)
1068
Peter Astrandc1d65362004-11-07 14:30:34 +00001069 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +00001070 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001071 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +00001072 if -1 not in (p2cread, c2pwrite, errwrite):
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001073 startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +00001074 startupinfo.hStdInput = p2cread
1075 startupinfo.hStdOutput = c2pwrite
1076 startupinfo.hStdError = errwrite
1077
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078 if shell:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001079 startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
1080 startupinfo.wShowWindow = _winapi.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +00001082 args = '{} /c "{}"'.format (comspec, args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001084 # Start the process
1085 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001086 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +00001087 # no special security
1088 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001089 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +00001090 creationflags,
1091 env,
1092 cwd,
1093 startupinfo)
Tim Goldenad537f22010-08-08 11:18:16 +00001094 finally:
1095 # Child is launched. Close the parent's copy of those pipe
1096 # handles that only the child should have open. You need
1097 # to make sure that no handles to the write end of the
1098 # output pipe are maintained in this process or else the
1099 # pipe will not close when the child process exits and the
1100 # ReadFile will hang.
1101 if p2cread != -1:
1102 p2cread.Close()
1103 if c2pwrite != -1:
1104 c2pwrite.Close()
1105 if errwrite != -1:
1106 errwrite.Close()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001107 if hasattr(self, '_devnull'):
1108 os.close(self._devnull)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109
1110 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001111 self._child_created = True
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001112 self._handle = Handle(hp)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001113 self.pid = pid
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001114 _winapi.CloseHandle(ht)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001115
Brett Cannon84df1e62010-05-14 00:33:40 +00001116 def _internal_poll(self, _deadstate=None,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001117 _WaitForSingleObject=_winapi.WaitForSingleObject,
1118 _WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
1119 _GetExitCodeProcess=_winapi.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001120 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001121 attribute.
1122
1123 This method is called by __del__, so it can only refer to objects
1124 in its local scope.
1125
1126 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001127 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001128 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1129 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001130 return self.returncode
1131
1132
Reid Kleckner2b228f02011-03-16 16:57:54 -04001133 def wait(self, timeout=None, endtime=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 """Wait for child process to terminate. Returns returncode
1135 attribute."""
Reid Kleckner2b228f02011-03-16 16:57:54 -04001136 if endtime is not None:
1137 timeout = self._remaining_time(endtime)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001138 if timeout is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001139 timeout_millis = _winapi.INFINITE
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001140 else:
Reid Kleckner91156ff2011-03-21 10:06:10 -07001141 timeout_millis = int(timeout * 1000)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001142 if self.returncode is None:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001143 result = _winapi.WaitForSingleObject(self._handle,
1144 timeout_millis)
1145 if result == _winapi.WAIT_TIMEOUT:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001146 raise TimeoutExpired(self.args, timeout)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001147 self.returncode = _winapi.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001148 return self.returncode
1149
1150
1151 def _readerthread(self, fh, buffer):
1152 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001153 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001154
1155
Reid Kleckner2b228f02011-03-16 16:57:54 -04001156 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001157 # Start reader threads feeding into a list hanging off of this
1158 # object, unless they've already been started.
1159 if self.stdout and not hasattr(self, "_stdout_buff"):
1160 self._stdout_buff = []
1161 self.stdout_thread = \
1162 threading.Thread(target=self._readerthread,
1163 args=(self.stdout, self._stdout_buff))
1164 self.stdout_thread.daemon = True
1165 self.stdout_thread.start()
1166 if self.stderr and not hasattr(self, "_stderr_buff"):
1167 self._stderr_buff = []
1168 self.stderr_thread = \
1169 threading.Thread(target=self._readerthread,
1170 args=(self.stderr, self._stderr_buff))
1171 self.stderr_thread.daemon = True
1172 self.stderr_thread.start()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001173
1174 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +00001175 if input is not None:
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001176 try:
1177 self.stdin.write(input)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001178 except OSError as e:
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001179 if e.errno != errno.EPIPE:
1180 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001181 self.stdin.close()
1182
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001183 # Wait for the reader threads, or time out. If we time out, the
1184 # threads remain reading and the fds left open in case the user
1185 # calls communicate again.
1186 if self.stdout is not None:
1187 self.stdout_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001188 if self.stdout_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001189 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001190 if self.stderr is not None:
1191 self.stderr_thread.join(self._remaining_time(endtime))
Andrew Svetlov377a1522012-08-19 20:49:39 +03001192 if self.stderr_thread.is_alive():
Reid Kleckner9a67e6c2011-03-20 08:28:07 -07001193 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001194
1195 # Collect the output from and close both pipes, now that we know
1196 # both have been read successfully.
1197 stdout = None
1198 stderr = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001199 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001200 stdout = self._stdout_buff
1201 self.stdout.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001202 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001203 stderr = self._stderr_buff
1204 self.stderr.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001205
1206 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001207 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001208 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001209 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001210 stderr = stderr[0]
1211
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001212 return (stdout, stderr)
1213
Christian Heimesa342c012008-04-20 21:01:16 +00001214 def send_signal(self, sig):
1215 """Send a signal to the process
1216 """
1217 if sig == signal.SIGTERM:
1218 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001219 elif sig == signal.CTRL_C_EVENT:
1220 os.kill(self.pid, signal.CTRL_C_EVENT)
1221 elif sig == signal.CTRL_BREAK_EVENT:
1222 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001223 else:
Brian Curtin19651362010-09-07 13:24:38 +00001224 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001225
1226 def terminate(self):
1227 """Terminates the process
1228 """
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001229 try:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001230 _winapi.TerminateProcess(self._handle, 1)
Antoine Pitroub69ef162012-03-11 19:33:29 +01001231 except PermissionError:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001232 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1233 # process already died.
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001234 rc = _winapi.GetExitCodeProcess(self._handle)
1235 if rc == _winapi.STILL_ACTIVE:
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001236 raise
1237 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001238
1239 kill = terminate
1240
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001241 else:
1242 #
1243 # POSIX methods
1244 #
1245 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001246 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001247 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1248 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001249 p2cread, p2cwrite = -1, -1
1250 c2pread, c2pwrite = -1, -1
1251 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001252
Peter Astrandd38ddf42005-02-10 08:32:50 +00001253 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001254 pass
1255 elif stdin == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001256 p2cread, p2cwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001257 elif stdin == DEVNULL:
1258 p2cread = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001259 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001260 p2cread = stdin
1261 else:
1262 # Assuming file-like object
1263 p2cread = stdin.fileno()
1264
Peter Astrandd38ddf42005-02-10 08:32:50 +00001265 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001266 pass
1267 elif stdout == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001268 c2pread, c2pwrite = os.pipe()
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001269 elif stdout == DEVNULL:
1270 c2pwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001271 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001272 c2pwrite = stdout
1273 else:
1274 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001275 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001276
Peter Astrandd38ddf42005-02-10 08:32:50 +00001277 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001278 pass
1279 elif stderr == PIPE:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001280 errread, errwrite = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001281 elif stderr == STDOUT:
1282 errwrite = c2pwrite
Ross Lagerwallba102ec2011-03-16 18:40:25 +02001283 elif stderr == DEVNULL:
1284 errwrite = self._get_devnull()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001285 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001286 errwrite = stderr
1287 else:
1288 # Assuming file-like object
1289 errwrite = stderr.fileno()
1290
1291 return (p2cread, p2cwrite,
1292 c2pread, c2pwrite,
1293 errread, errwrite)
1294
1295
Antoine Pitrou47f14ba2011-01-03 23:42:01 +00001296 def _close_fds(self, fds_to_keep):
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001297 start_fd = 3
Antoine Pitrou47f14ba2011-01-03 23:42:01 +00001298 for fd in sorted(fds_to_keep):
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001299 if fd >= start_fd:
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001300 os.closerange(start_fd, fd)
1301 start_fd = fd + 1
1302 if start_fd <= MAXFD:
1303 os.closerange(start_fd, MAXFD)
1304
1305
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001306 def _execute_child(self, args, executable, preexec_fn, close_fds,
Andrew Svetlov592df202012-08-15 17:36:15 +03001307 pass_fds, cwd, env,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001308 startupinfo, creationflags, shell,
1309 p2cread, p2cwrite,
1310 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001311 errread, errwrite,
1312 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001313 """Execute program (POSIX version)"""
1314
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001315 if isinstance(args, (str, bytes)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001316 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001317 else:
1318 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001319
1320 if shell:
1321 args = ["/bin/sh", "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001322 if executable:
1323 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001324
Peter Astrandd38ddf42005-02-10 08:32:50 +00001325 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001326 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001327 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001328
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001329 # For transferring possible exec failure from child to parent.
1330 # Data format: "exception name:hex errno:description"
1331 # Pickle is not used; it is complex and involves memory allocation.
Victor Stinnerdaf45552013-08-28 00:53:59 +02001332 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001333 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001334 try:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001335 # We must avoid complex work that could involve
1336 # malloc or free in the child process to avoid
1337 # potential deadlocks, thus we do all this here.
1338 # and pass it to fork_exec()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001339
Victor Stinner372b8382011-06-21 17:24:21 +02001340 if env is not None:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001341 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
1342 for k, v in env.items()]
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001343 else:
Gregory P. Smith59fd1bf2011-05-28 09:32:39 -07001344 env_list = None # Use execv instead of execve.
1345 executable = os.fsencode(executable)
1346 if os.path.dirname(executable):
1347 executable_list = (executable,)
1348 else:
1349 # This matches the behavior of os._execvpe().
1350 executable_list = tuple(
1351 os.path.join(os.fsencode(dir), executable)
1352 for dir in os.get_exec_path(env))
1353 fds_to_keep = set(pass_fds)
1354 fds_to_keep.add(errpipe_write)
1355 self.pid = _posixsubprocess.fork_exec(
1356 args, executable_list,
1357 close_fds, sorted(fds_to_keep), cwd, env_list,
1358 p2cread, p2cwrite, c2pread, c2pwrite,
1359 errread, errwrite,
1360 errpipe_read, errpipe_write,
1361 restore_signals, start_new_session, preexec_fn)
Charles-François Natali558639f2011-08-18 19:11:29 +02001362 self._child_created = True
Facundo Batista10706e22009-06-19 20:34:30 +00001363 finally:
1364 # be sure the FD is closed no matter what
1365 os.close(errpipe_write)
1366
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001367 # self._devnull is not always defined.
1368 devnull_fd = getattr(self, '_devnull', None)
1369 if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001370 os.close(p2cread)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001371 if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001372 os.close(c2pwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001373 if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
Facundo Batista10706e22009-06-19 20:34:30 +00001374 os.close(errwrite)
Gregory P. Smithb5461b92013-06-15 18:04:26 -07001375 if devnull_fd is not None:
1376 os.close(devnull_fd)
1377 # Prevent a double close of these fds from __init__ on error.
1378 self._closed_child_pipe_fds = True
Facundo Batista10706e22009-06-19 20:34:30 +00001379
1380 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001381 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001382 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001383 while True:
1384 part = _eintr_retry_call(os.read, errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001385 errpipe_data += part
1386 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001387 break
Facundo Batista10706e22009-06-19 20:34:30 +00001388 finally:
1389 # be sure the FD is closed no matter what
1390 os.close(errpipe_read)
1391
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001392 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001393 try:
1394 _eintr_retry_call(os.waitpid, self.pid, 0)
1395 except OSError as e:
1396 if e.errno != errno.ECHILD:
1397 raise
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001398 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001399 exception_name, hex_errno, err_msg = (
1400 errpipe_data.split(b':', 2))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001401 except ValueError:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001402 exception_name = b'SubprocessError'
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001403 hex_errno = b'0'
Gregory P. Smith3aee2222012-11-11 00:04:13 -08001404 err_msg = (b'Bad exception data from child: ' +
1405 repr(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001406 child_exception_type = getattr(
1407 builtins, exception_name.decode('ascii'),
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001408 SubprocessError)
Victor Stinner4d078042010-04-23 19:28:32 +00001409 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001410 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001411 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001412 child_exec_never_called = (err_msg == "noexec")
1413 if child_exec_never_called:
1414 err_msg = ""
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001415 if errno_num != 0:
1416 err_msg = os.strerror(errno_num)
1417 if errno_num == errno.ENOENT:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001418 if child_exec_never_called:
1419 # The error must be from chdir(cwd).
1420 err_msg += ': ' + repr(cwd)
1421 else:
1422 err_msg += ': ' + repr(orig_executable)
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001423 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001424 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001425
1426
Brett Cannon84df1e62010-05-14 00:33:40 +00001427 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1428 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1429 _WEXITSTATUS=os.WEXITSTATUS):
1430 # This method is called (indirectly) by __del__, so it cannot
1431 # refer to anything outside of its local scope."""
1432 if _WIFSIGNALED(sts):
1433 self.returncode = -_WTERMSIG(sts)
1434 elif _WIFEXITED(sts):
1435 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001436 else:
1437 # Should never happen
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001438 raise SubprocessError("Unknown child exit status!")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001439
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001440
Brett Cannon84df1e62010-05-14 00:33:40 +00001441 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov1d960fe2012-12-24 20:08:53 +02001442 _WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001443 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001444 attribute.
1445
1446 This method is called by __del__, so it cannot reference anything
1447 outside of the local scope (nor can any methods it calls).
1448
1449 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001450 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001451 try:
Brett Cannon84df1e62010-05-14 00:33:40 +00001452 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001453 if pid == self.pid:
1454 self._handle_exitstatus(sts)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001455 except OSError as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001456 if _deadstate is not None:
1457 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001458 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001459 # This happens if SIGCLD is set to be ignored or
1460 # waiting for child processes has otherwise been
1461 # disabled for our process. This child is dead, we
1462 # can't get the status.
1463 # http://bugs.python.org/issue15756
1464 self.returncode = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001465 return self.returncode
1466
1467
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001468 def _try_wait(self, wait_flags):
1469 try:
1470 (pid, sts) = _eintr_retry_call(os.waitpid, self.pid, wait_flags)
1471 except OSError as e:
1472 if e.errno != errno.ECHILD:
1473 raise
1474 # This happens if SIGCLD is set to be ignored or waiting
1475 # for child processes has otherwise been disabled for our
1476 # process. This child is dead, we can't get the status.
1477 pid = self.pid
1478 sts = 0
1479 return (pid, sts)
1480
1481
1482 def wait(self, timeout=None, endtime=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001483 """Wait for child process to terminate. Returns returncode
1484 attribute."""
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001485 if self.returncode is not None:
1486 return self.returncode
Reid Kleckner2b228f02011-03-16 16:57:54 -04001487
1488 # endtime is preferred to timeout. timeout is only used for
1489 # printing.
1490 if endtime is not None or timeout is not None:
1491 if endtime is None:
Victor Stinner949d8c92012-05-30 13:30:32 +02001492 endtime = _time() + timeout
Reid Kleckner2b228f02011-03-16 16:57:54 -04001493 elif timeout is None:
1494 timeout = self._remaining_time(endtime)
1495
1496 if endtime is not None:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001497 # Enter a busy loop if we have a timeout. This busy loop was
1498 # cribbed from Lib/threading.py in Thread.wait() at r71065.
1499 delay = 0.0005 # 500 us -> initial delay of 1 ms
1500 while True:
1501 (pid, sts) = self._try_wait(os.WNOHANG)
1502 assert pid == self.pid or pid == 0
1503 if pid == self.pid:
1504 self._handle_exitstatus(sts)
1505 break
1506 remaining = self._remaining_time(endtime)
1507 if remaining <= 0:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001508 raise TimeoutExpired(self.args, timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001509 delay = min(delay * 2, remaining, .05)
1510 time.sleep(delay)
Gregory P. Smithf328d792012-11-10 21:06:18 -08001511 else:
1512 while self.returncode is None:
1513 (pid, sts) = self._try_wait(0)
1514 # Check the pid and loop as waitpid has been known to return
1515 # 0 even without WNOHANG in odd situations. issue14396.
1516 if pid == self.pid:
1517 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001518 return self.returncode
1519
1520
Reid Kleckner2b228f02011-03-16 16:57:54 -04001521 def _communicate(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001522 if self.stdin and not self._communication_started:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001523 # Flush stdio buffer. This might block, if the user has
1524 # been writing to .stdin in an uncontrolled fashion.
1525 self.stdin.flush()
1526 if not input:
1527 self.stdin.close()
1528
1529 if _has_poll:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001530 stdout, stderr = self._communicate_with_poll(input, endtime,
1531 orig_timeout)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001532 else:
Reid Kleckner2b228f02011-03-16 16:57:54 -04001533 stdout, stderr = self._communicate_with_select(input, endtime,
1534 orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001535
1536 self.wait(timeout=self._remaining_time(endtime))
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001537
1538 # All data exchanged. Translate lists into strings.
1539 if stdout is not None:
1540 stdout = b''.join(stdout)
1541 if stderr is not None:
1542 stderr = b''.join(stderr)
1543
1544 # Translate newlines, if requested.
1545 # This also turns bytes into strings.
1546 if self.universal_newlines:
1547 if stdout is not None:
1548 stdout = self._translate_newlines(stdout,
1549 self.stdout.encoding)
1550 if stderr is not None:
1551 stderr = self._translate_newlines(stderr,
1552 self.stderr.encoding)
1553
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001554 return (stdout, stderr)
1555
1556
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001557 def _save_input(self, input):
1558 # This method is called from the _communicate_with_*() methods
1559 # so that if we time out while communicating, we can continue
1560 # sending input if we retry.
1561 if self.stdin and self._input is None:
1562 self._input_offset = 0
1563 self._input = input
1564 if self.universal_newlines and input is not None:
1565 self._input = self._input.encode(self.stdin.encoding)
1566
1567
Reid Kleckner2b228f02011-03-16 16:57:54 -04001568 def _communicate_with_poll(self, input, endtime, orig_timeout):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001569 stdout = None # Return
1570 stderr = None # Return
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001571
1572 if not self._communication_started:
1573 self._fd2file = {}
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001574
1575 poller = select.poll()
1576 def register_and_append(file_obj, eventmask):
1577 poller.register(file_obj.fileno(), eventmask)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001578 self._fd2file[file_obj.fileno()] = file_obj
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001579
1580 def close_unregister_and_remove(fd):
1581 poller.unregister(fd)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001582 self._fd2file[fd].close()
1583 self._fd2file.pop(fd)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001584
1585 if self.stdin and input:
1586 register_and_append(self.stdin, select.POLLOUT)
1587
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001588 # Only create this mapping if we haven't already.
1589 if not self._communication_started:
1590 self._fd2output = {}
1591 if self.stdout:
1592 self._fd2output[self.stdout.fileno()] = []
1593 if self.stderr:
1594 self._fd2output[self.stderr.fileno()] = []
1595
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001596 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1597 if self.stdout:
1598 register_and_append(self.stdout, select_POLLIN_POLLPRI)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001599 stdout = self._fd2output[self.stdout.fileno()]
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001600 if self.stderr:
1601 register_and_append(self.stderr, select_POLLIN_POLLPRI)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001602 stderr = self._fd2output[self.stderr.fileno()]
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001603
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001604 self._save_input(input)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001605
1606 while self._fd2file:
Victor Stinner7a8d0812011-04-05 13:13:08 +02001607 timeout = self._remaining_time(endtime)
1608 if timeout is not None and timeout < 0:
1609 raise TimeoutExpired(self.args, orig_timeout)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001610 try:
Victor Stinner7a8d0812011-04-05 13:13:08 +02001611 ready = poller.poll(timeout)
Andrew Svetlov6d8a1222012-12-17 22:23:46 +02001612 except OSError as e:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001613 if e.args[0] == errno.EINTR:
1614 continue
1615 raise
Reid Kleckner2b228f02011-03-16 16:57:54 -04001616 self._check_timeout(endtime, orig_timeout)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001617
1618 # XXX Rewrite these to use non-blocking I/O on the
1619 # file objects; they are no longer using C stdio!
1620
1621 for fd, mode in ready:
1622 if mode & select.POLLOUT:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001623 chunk = self._input[self._input_offset :
1624 self._input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001625 try:
Ross Lagerwall0b9ea932011-04-05 16:07:49 +02001626 self._input_offset += os.write(fd, chunk)
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001627 except OSError as e:
1628 if e.errno == errno.EPIPE:
1629 close_unregister_and_remove(fd)
1630 else:
1631 raise
1632 else:
Ross Lagerwall0b9ea932011-04-05 16:07:49 +02001633 if self._input_offset >= len(self._input):
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001634 close_unregister_and_remove(fd)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001635 elif mode & select_POLLIN_POLLPRI:
1636 data = os.read(fd, 4096)
1637 if not data:
1638 close_unregister_and_remove(fd)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001639 self._fd2output[fd].append(data)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001640 else:
1641 # Ignore hang up or errors.
1642 close_unregister_and_remove(fd)
1643
1644 return (stdout, stderr)
1645
1646
Reid Kleckner2b228f02011-03-16 16:57:54 -04001647 def _communicate_with_select(self, input, endtime, orig_timeout):
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001648 if not self._communication_started:
1649 self._read_set = []
1650 self._write_set = []
1651 if self.stdin and input:
1652 self._write_set.append(self.stdin)
1653 if self.stdout:
1654 self._read_set.append(self.stdout)
1655 if self.stderr:
1656 self._read_set.append(self.stderr)
1657
Andrew Svetlovaa0dbdc2012-08-14 18:40:21 +03001658 self._save_input(input)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001659
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001660 stdout = None # Return
1661 stderr = None # Return
1662
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001663 if self.stdout:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001664 if not self._communication_started:
1665 self._stdout_buff = []
1666 stdout = self._stdout_buff
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001667 if self.stderr:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001668 if not self._communication_started:
1669 self._stderr_buff = []
1670 stderr = self._stderr_buff
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001671
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001672 while self._read_set or self._write_set:
Victor Stinner7a8d0812011-04-05 13:13:08 +02001673 timeout = self._remaining_time(endtime)
1674 if timeout is not None and timeout < 0:
1675 raise TimeoutExpired(self.args, orig_timeout)
Georg Brandl86b2fb92008-07-16 03:43:04 +00001676 try:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001677 (rlist, wlist, xlist) = \
1678 select.select(self._read_set, self._write_set, [],
Victor Stinner7a8d0812011-04-05 13:13:08 +02001679 timeout)
Andrew Svetlov6d8a1222012-12-17 22:23:46 +02001680 except OSError as e:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001681 if e.args[0] == errno.EINTR:
1682 continue
1683 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001684
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001685 # According to the docs, returning three empty lists indicates
1686 # that the timeout expired.
1687 if not (rlist or wlist or xlist):
Reid Kleckner2b228f02011-03-16 16:57:54 -04001688 raise TimeoutExpired(self.args, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001689 # We also check what time it is ourselves for good measure.
Reid Kleckner2b228f02011-03-16 16:57:54 -04001690 self._check_timeout(endtime, orig_timeout)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001691
Guido van Rossum98297ee2007-11-06 21:34:58 +00001692 # XXX Rewrite these to use non-blocking I/O on the
1693 # file objects; they are no longer using C stdio!
1694
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001695 if self.stdin in wlist:
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001696 chunk = self._input[self._input_offset :
1697 self._input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001698 try:
1699 bytes_written = os.write(self.stdin.fileno(), chunk)
1700 except OSError as e:
1701 if e.errno == errno.EPIPE:
1702 self.stdin.close()
Ross Lagerwall0b9ea932011-04-05 16:07:49 +02001703 self._write_set.remove(self.stdin)
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001704 else:
1705 raise
1706 else:
Ross Lagerwall0b9ea932011-04-05 16:07:49 +02001707 self._input_offset += bytes_written
1708 if self._input_offset >= len(self._input):
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001709 self.stdin.close()
Ross Lagerwall0b9ea932011-04-05 16:07:49 +02001710 self._write_set.remove(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001711
1712 if self.stdout in rlist:
1713 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001714 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001715 self.stdout.close()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001716 self._read_set.remove(self.stdout)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001717 stdout.append(data)
1718
1719 if self.stderr in rlist:
1720 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001721 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001722 self.stderr.close()
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001723 self._read_set.remove(self.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001724 stderr.append(data)
1725
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001726 return (stdout, stderr)
1727
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001728
Christian Heimesa342c012008-04-20 21:01:16 +00001729 def send_signal(self, sig):
1730 """Send a signal to the process
1731 """
1732 os.kill(self.pid, sig)
1733
1734 def terminate(self):
1735 """Terminate the process with SIGTERM
1736 """
1737 self.send_signal(signal.SIGTERM)
1738
1739 def kill(self):
1740 """Kill the process with SIGKILL
1741 """
1742 self.send_signal(signal.SIGKILL)