blob: 4b41f5ec5c7eb2cc9bd38b6a273b5c7bff1d172b [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001# subprocess - Subprocesses with accessible I/O streams
2#
Tim Peterse718f612004-10-12 21:51:32 +00003# For more information about this module, see PEP 324.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004#
Peter Astrand3a708df2005-09-23 17:37:29 +00005# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006#
Peter Astrand69bf13f2005-02-14 08:56:32 +00007# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +00008# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009
Martin Panter5e5af962016-10-26 00:44:31 +000010r"""Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000012This module allows you to spawn processes, connect to their
Martin Panter5e5af962016-10-26 00:44:31 +000013input/output/error pipes, and obtain their return codes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014
Martin Panter5e5af962016-10-26 00:44:31 +000015For a complete description of this module see the Python documentation.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000016
Martin Panter5e5af962016-10-26 00:44:31 +000017Main API
18========
19call(...): Runs a command, waits for it to complete, then returns
20 the return code.
21check_call(...): Same as call() but raises CalledProcessError()
22 if return code is not 0
23check_output(...): Same as check_call() but returns the contents of
24 stdout instead of a return code
25Popen(...): A class for flexibly executing a command in a new process
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026
Martin Panter5e5af962016-10-26 00:44:31 +000027Constants
28---------
29PIPE: Special value that indicates a pipe should be created
30STDOUT: Special value that indicates that stderr should go to stdout
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000031"""
32
33import sys
34mswindows = (sys.platform == "win32")
35
36import os
Peter Astrandc26516b2005-02-21 08:13:02 +000037import types
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000038import traceback
Gregory P. Smith87d49792008-01-19 20:57:59 +000039import gc
Christian Heimese74c8f22008-04-19 02:23:57 +000040import signal
Ross Lagerwall104c3f12011-04-05 15:24:34 +020041import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042
Peter Astrand454f7672005-01-01 09:36:35 +000043# Exception classes used by this module.
Peter Astrand7d1d4362006-07-14 14:04:45 +000044class CalledProcessError(Exception):
Gregory P. Smith97f49f42008-12-04 20:21:09 +000045 """This exception is raised when a process run by check_call() or
Gregory P. Smith26576802008-12-05 02:27:01 +000046 check_output() returns a non-zero exit status.
Martin Panter5e5af962016-10-26 00:44:31 +000047
48 Attributes:
49 cmd, returncode, output
Gregory P. Smith97f49f42008-12-04 20:21:09 +000050 """
51 def __init__(self, returncode, cmd, output=None):
Peter Astrand7d1d4362006-07-14 14:04:45 +000052 self.returncode = returncode
53 self.cmd = cmd
Gregory P. Smith97f49f42008-12-04 20:21:09 +000054 self.output = output
Peter Astrand7d1d4362006-07-14 14:04:45 +000055 def __str__(self):
56 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
Tim Peters73a9ead2006-07-18 21:55:15 +000057
Peter Astrand454f7672005-01-01 09:36:35 +000058
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059if mswindows:
60 import threading
61 import msvcrt
Brian Curtina2936cf2010-04-24 15:40:11 +000062 import _subprocess
63 class STARTUPINFO:
64 dwFlags = 0
65 hStdInput = None
66 hStdOutput = None
67 hStdError = None
68 wShowWindow = 0
69 class pywintypes:
70 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000071else:
72 import select
Gregory P. Smithdd7ca242009-07-04 01:49:29 +000073 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000074 import fcntl
75 import pickle
76
Amaury Forgeot d'Arcce32eb72009-07-09 22:37:22 +000077 # When select or poll has indicated that the file is writable,
78 # we can write up to _PIPE_BUF bytes without risk of blocking.
79 # POSIX defines PIPE_BUF as >= 512.
80 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
81
82
Gregory P. Smith97f49f42008-12-04 20:21:09 +000083__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
Gregory P. Smith26576802008-12-05 02:27:01 +000084 "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000085
Brian Curtina2936cf2010-04-24 15:40:11 +000086if mswindows:
Brian Curtin77b75912011-04-29 16:21:51 -050087 from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
88 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
89 STD_ERROR_HANDLE, SW_HIDE,
90 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Brian Curtin20de4582011-04-29 16:28:52 -050091
Brian Curtin77b75912011-04-29 16:21:51 -050092 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
93 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
94 "STD_ERROR_HANDLE", "SW_HIDE",
95 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000096try:
97 MAXFD = os.sysconf("SC_OPEN_MAX")
98except:
99 MAXFD = 256
100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000101_active = []
102
103def _cleanup():
104 for inst in _active[:]:
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000105 res = inst._internal_poll(_deadstate=sys.maxint)
Charles-François Natalib02302c2011-08-18 17:18:28 +0200106 if res is not None:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000107 try:
108 _active.remove(inst)
109 except ValueError:
110 # This can happen if two threads create a new Popen instance.
111 # It's harmless that it was already removed, so ignore.
112 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000113
114PIPE = -1
115STDOUT = -2
116
117
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000118def _eintr_retry_call(func, *args):
119 while True:
120 try:
121 return func(*args)
Victor Stinnere7901312011-07-05 14:08:01 +0200122 except (OSError, IOError) as e:
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000123 if e.errno == errno.EINTR:
124 continue
125 raise
126
127
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700128# XXX This function is only used by multiprocessing and the test suite,
129# but it's here so that it can be imported when Python is compiled without
130# threads.
131
132def _args_from_interpreter_flags():
133 """Return a list of command-line arguments reproducing the current
134 settings in sys.flags and sys.warnoptions."""
135 flag_opt_map = {
136 'debug': 'd',
137 # 'inspect': 'i',
138 # 'interactive': 'i',
139 'optimize': 'O',
140 'dont_write_bytecode': 'B',
141 'no_user_site': 's',
142 'no_site': 'S',
143 'ignore_environment': 'E',
144 'verbose': 'v',
145 'bytes_warning': 'b',
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700146 'py3k_warning': '3',
147 }
148 args = []
149 for flag, opt in flag_opt_map.items():
150 v = getattr(sys.flags, flag)
151 if v > 0:
152 args.append('-' + opt * v)
Gregory P. Smith64fa45a2015-12-13 13:57:50 -0800153 if getattr(sys.flags, 'hash_randomization') != 0:
154 args.append('-R')
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700155 for opt in sys.warnoptions:
156 args.append('-W' + opt)
157 return args
158
159
Peter Astrand5f5e1412004-12-05 20:15:36 +0000160def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 """Run command with arguments. Wait for command to complete, then
162 return the returncode attribute.
163
164 The arguments are the same as for the Popen constructor. Example:
165
166 retcode = call(["ls", "-l"])
167 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000168 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169
170
Peter Astrand454f7672005-01-01 09:36:35 +0000171def check_call(*popenargs, **kwargs):
172 """Run command with arguments. Wait for command to complete. If
173 the exit code was zero then return, otherwise raise
174 CalledProcessError. The CalledProcessError object will have the
Peter Astrand7d1d4362006-07-14 14:04:45 +0000175 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000176
177 The arguments are the same as for the Popen constructor. Example:
178
179 check_call(["ls", "-l"])
180 """
181 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000182 if retcode:
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000183 cmd = kwargs.get("args")
184 if cmd is None:
185 cmd = popenargs[0]
Peter Astrand7d1d4362006-07-14 14:04:45 +0000186 raise CalledProcessError(retcode, cmd)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000187 return 0
188
189
Gregory P. Smith26576802008-12-05 02:27:01 +0000190def check_output(*popenargs, **kwargs):
Georg Brandl6ab5d082009-12-20 14:33:20 +0000191 r"""Run command with arguments and return its output as a byte string.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000192
193 If the exit code was non-zero it raises a CalledProcessError. The
194 CalledProcessError object will have the return code in the returncode
195 attribute and output in the output attribute.
196
197 The arguments are the same as for the Popen constructor. Example:
198
Gregory P. Smith26576802008-12-05 02:27:01 +0000199 >>> check_output(["ls", "-l", "/dev/null"])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000200 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
201
202 The stdout argument is not allowed as it is used internally.
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000203 To capture standard error in the result, use stderr=STDOUT.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000204
Gregory P. Smith26576802008-12-05 02:27:01 +0000205 >>> check_output(["/bin/sh", "-c",
Georg Brandl6ab5d082009-12-20 14:33:20 +0000206 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000207 ... stderr=STDOUT)
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000208 'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000209 """
210 if 'stdout' in kwargs:
211 raise ValueError('stdout argument not allowed, it will be overridden.')
Amaury Forgeot d'Arc5fe420e2009-06-18 22:32:50 +0000212 process = Popen(stdout=PIPE, *popenargs, **kwargs)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000213 output, unused_err = process.communicate()
214 retcode = process.poll()
215 if retcode:
216 cmd = kwargs.get("args")
217 if cmd is None:
218 cmd = popenargs[0]
219 raise CalledProcessError(retcode, cmd, output=output)
220 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000221
222
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223def list2cmdline(seq):
224 """
225 Translate a sequence of arguments into a command line
226 string, using the same rules as the MS C runtime:
227
228 1) Arguments are delimited by white space, which is either a
229 space or a tab.
230
231 2) A string surrounded by double quotation marks is
232 interpreted as a single argument, regardless of white space
Jean-Paul Calderoneb33f0c12010-06-18 20:00:17 +0000233 contained within. A quoted string can be embedded in an
234 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235
236 3) A double quotation mark preceded by a backslash is
237 interpreted as a literal double quotation mark.
238
239 4) Backslashes are interpreted literally, unless they
240 immediately precede a double quotation mark.
241
242 5) If backslashes immediately precede a double quotation mark,
243 every pair of backslashes is interpreted as a literal
244 backslash. If the number of backslashes is odd, the last
245 backslash escapes the next double quotation mark as
246 described in rule 3.
247 """
248
249 # See
Eric Smithd19915e2009-11-09 15:16:23 +0000250 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
251 # or search http://msdn.microsoft.com for
252 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 result = []
254 needquote = False
255 for arg in seq:
256 bs_buf = []
257
258 # Add a space to separate this argument from the others
259 if result:
260 result.append(' ')
261
Jean-Paul Calderoneb33f0c12010-06-18 20:00:17 +0000262 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 if needquote:
264 result.append('"')
265
266 for c in arg:
267 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000268 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 bs_buf.append(c)
270 elif c == '"':
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000271 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272 result.append('\\' * len(bs_buf)*2)
273 bs_buf = []
274 result.append('\\"')
275 else:
276 # Normal char
277 if bs_buf:
278 result.extend(bs_buf)
279 bs_buf = []
280 result.append(c)
281
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000282 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 if bs_buf:
284 result.extend(bs_buf)
285
286 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000287 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 result.append('"')
289
290 return ''.join(result)
291
292
293class Popen(object):
Martin Panter5e5af962016-10-26 00:44:31 +0000294 """ Execute a child program in a new process.
295
296 For a complete description of the arguments see the Python documentation.
297
298 Arguments:
299 args: A string, or a sequence of program arguments.
300
301 bufsize: supplied as the buffering argument to the open() function when
302 creating the stdin/stdout/stderr pipe file objects
303
304 executable: A replacement program to execute.
305
306 stdin, stdout and stderr: These specify the executed programs' standard
307 input, standard output and standard error file handles, respectively.
308
309 preexec_fn: (POSIX only) An object to be called in the child process
310 just before the child is executed.
311
312 close_fds: Controls closing or inheriting of file descriptors.
313
314 shell: If true, the command will be executed through the shell.
315
316 cwd: Sets the current directory before the child is executed.
317
318 env: Defines the environment variables for the new process.
319
320 universal_newlines: If true, use universal line endings for file
321 objects stdin, stdout and stderr.
322
323 startupinfo and creationflags (Windows only)
324
325 Attributes:
326 stdin, stdout, stderr, pid, returncode
327 """
Serhiy Storchaka30615852014-02-10 19:19:53 +0200328 _child_created = False # Set here since __del__ checks it
329
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 def __init__(self, args, bufsize=0, executable=None,
331 stdin=None, stdout=None, stderr=None,
332 preexec_fn=None, close_fds=False, shell=False,
333 cwd=None, env=None, universal_newlines=False,
334 startupinfo=None, creationflags=0):
335 """Create new Popen instance."""
336 _cleanup()
337
Peter Astrand738131d2004-11-30 21:04:45 +0000338 if not isinstance(bufsize, (int, long)):
339 raise TypeError("bufsize must be an integer")
340
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000342 if preexec_fn is not None:
343 raise ValueError("preexec_fn is not supported on Windows "
344 "platforms")
Peter Astrand81a191b2007-05-26 22:18:20 +0000345 if close_fds and (stdin is not None or stdout is not None or
346 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000347 raise ValueError("close_fds is not supported on Windows "
Peter Astrand81a191b2007-05-26 22:18:20 +0000348 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 else:
350 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000351 if startupinfo is not None:
352 raise ValueError("startupinfo is only supported on Windows "
353 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000355 raise ValueError("creationflags is only supported on Windows "
356 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000357
Tim Peterse718f612004-10-12 21:51:32 +0000358 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 self.stdout = None
360 self.stderr = None
361 self.pid = None
362 self.returncode = None
363 self.universal_newlines = universal_newlines
364
365 # Input and output objects. The general principle is like
366 # this:
367 #
368 # Parent Child
369 # ------ -----
370 # p2cwrite ---stdin---> p2cread
371 # c2pread <--stdout--- c2pwrite
372 # errread <--stderr--- errwrite
373 #
374 # On POSIX, the child objects are file descriptors. On
375 # Windows, these are Windows file handles. The parent objects
376 # are file descriptors on both platforms. The parent objects
377 # are None when not using PIPEs. The child objects are None
378 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000379
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 (p2cread, p2cwrite,
381 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200382 errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800384 try:
385 self._execute_child(args, executable, preexec_fn, close_fds,
386 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200387 startupinfo, creationflags, shell, to_close,
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800388 p2cread, p2cwrite,
389 c2pread, c2pwrite,
390 errread, errwrite)
391 except Exception:
392 # Preserve original exception in case os.close raises.
393 exc_type, exc_value, exc_trace = sys.exc_info()
394
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800395 for fd in to_close:
396 try:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200397 if mswindows:
398 fd.Close()
399 else:
400 os.close(fd)
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800401 except EnvironmentError:
402 pass
403
404 raise exc_type, exc_value, exc_trace
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405
Peter Astrand5f9c6ae2007-02-06 15:37:50 +0000406 if mswindows:
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000407 if p2cwrite is not None:
408 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
409 if c2pread is not None:
410 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
411 if errread is not None:
412 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Peter Astrand5f9c6ae2007-02-06 15:37:50 +0000413
Peter Astrandf5400032007-02-02 19:06:36 +0000414 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
Peter Astrandf5400032007-02-02 19:06:36 +0000416 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 if universal_newlines:
418 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
419 else:
420 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
Peter Astrandf5400032007-02-02 19:06:36 +0000421 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 if universal_newlines:
423 self.stderr = os.fdopen(errread, 'rU', bufsize)
424 else:
425 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000426
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427
428 def _translate_newlines(self, data):
429 data = data.replace("\r\n", "\n")
430 data = data.replace("\r", "\n")
431 return data
432
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000433
Serhiy Storchaka30615852014-02-10 19:19:53 +0200434 def __del__(self, _maxint=sys.maxint):
Victor Stinner776e69b2011-06-01 01:03:00 +0200435 # If __init__ hasn't had a chance to execute (e.g. if it
436 # was passed an undeclared keyword argument), we don't
437 # have a _child_created attribute at all.
Serhiy Storchaka30615852014-02-10 19:19:53 +0200438 if not self._child_created:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000439 # We didn't get to successfully create a child process.
440 return
441 # In case the child hasn't been waited on, check if it's done.
Brett Cannon42a0ba72010-05-14 00:21:48 +0000442 self._internal_poll(_deadstate=_maxint)
Georg Brandl13cf38c2006-07-20 16:28:39 +0000443 if self.returncode is None and _active is not None:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000444 # Child is still running, keep us alive until we can wait on it.
445 _active.append(self)
446
447
Peter Astrand23109f02005-03-03 20:28:59 +0000448 def communicate(self, input=None):
449 """Interact with process: Send data to stdin. Read data from
450 stdout and stderr, until end-of-file is reached. Wait for
451 process to terminate. The optional input argument should be a
452 string to be sent to the child process, or None, if no data
453 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000454
Peter Astrand23109f02005-03-03 20:28:59 +0000455 communicate() returns a tuple (stdout, stderr)."""
456
457 # Optimization: If we are only using one pipe, or no pipe at
458 # all, using select() or threads is unnecessary.
459 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000460 stdout = None
461 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000462 if self.stdin:
463 if input:
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200464 try:
465 self.stdin.write(input)
466 except IOError as e:
467 if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
468 raise
Peter Astrand23109f02005-03-03 20:28:59 +0000469 self.stdin.close()
470 elif self.stdout:
Victor Stinnere7901312011-07-05 14:08:01 +0200471 stdout = _eintr_retry_call(self.stdout.read)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000472 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000473 elif self.stderr:
Victor Stinnere7901312011-07-05 14:08:01 +0200474 stderr = _eintr_retry_call(self.stderr.read)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000475 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000476 self.wait()
477 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000478
Peter Astrand23109f02005-03-03 20:28:59 +0000479 return self._communicate(input)
480
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481
Gregory P. Smitha36f8fe2008-08-04 00:13:29 +0000482 def poll(self):
Martin Panter5e5af962016-10-26 00:44:31 +0000483 """Check if child process has terminated. Set and return returncode
484 attribute."""
Gregory P. Smitha36f8fe2008-08-04 00:13:29 +0000485 return self._internal_poll()
486
487
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 if mswindows:
489 #
490 # Windows methods
491 #
492 def _get_handles(self, stdin, stdout, stderr):
Amaury Forgeot d'Arc8318afa2009-07-10 16:47:42 +0000493 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
495 """
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200496 to_close = set()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000497 if stdin is None and stdout is None and stderr is None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200498 return (None, None, None, None, None, None), to_close
Tim Peterse718f612004-10-12 21:51:32 +0000499
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 p2cread, p2cwrite = None, None
501 c2pread, c2pwrite = None, None
502 errread, errwrite = None, None
503
Peter Astrandd38ddf42005-02-10 08:32:50 +0000504 if stdin is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000505 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000506 if p2cread is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000507 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000508 elif stdin == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000509 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200510 elif isinstance(stdin, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 p2cread = msvcrt.get_osfhandle(stdin)
512 else:
513 # Assuming file-like object
514 p2cread = msvcrt.get_osfhandle(stdin.fileno())
515 p2cread = self._make_inheritable(p2cread)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200516 # We just duplicated the handle, it has to be closed at the end
517 to_close.add(p2cread)
518 if stdin == PIPE:
519 to_close.add(p2cwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520
Peter Astrandd38ddf42005-02-10 08:32:50 +0000521 if stdout is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000522 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000523 if c2pwrite is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000524 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000525 elif stdout == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000526 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200527 elif isinstance(stdout, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 c2pwrite = msvcrt.get_osfhandle(stdout)
529 else:
530 # Assuming file-like object
531 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
532 c2pwrite = self._make_inheritable(c2pwrite)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200533 # We just duplicated the handle, it has to be closed at the end
534 to_close.add(c2pwrite)
535 if stdout == PIPE:
536 to_close.add(c2pread)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537
Peter Astrandd38ddf42005-02-10 08:32:50 +0000538 if stderr is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000539 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000540 if errwrite is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000541 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000542 elif stderr == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000543 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 elif stderr == STDOUT:
545 errwrite = c2pwrite
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200546 elif isinstance(stderr, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 errwrite = msvcrt.get_osfhandle(stderr)
548 else:
549 # Assuming file-like object
550 errwrite = msvcrt.get_osfhandle(stderr.fileno())
551 errwrite = self._make_inheritable(errwrite)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200552 # We just duplicated the handle, it has to be closed at the end
553 to_close.add(errwrite)
554 if stderr == PIPE:
555 to_close.add(errread)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 return (p2cread, p2cwrite,
558 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200559 errread, errwrite), to_close
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
561
562 def _make_inheritable(self, handle):
563 """Return a duplicate of handle, which is inheritable"""
Brian Curtina2936cf2010-04-24 15:40:11 +0000564 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
565 handle, _subprocess.GetCurrentProcess(), 0, 1,
566 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567
568
569 def _find_w9xpopen(self):
570 """Find and return absolut path to w9xpopen.exe"""
Brian Curtina2936cf2010-04-24 15:40:11 +0000571 w9xpopen = os.path.join(
572 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000573 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 if not os.path.exists(w9xpopen):
575 # Eeek - file-not-found - possibly an embedding
576 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000577 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
578 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000580 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
581 "needed for Popen to work with your "
582 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 return w9xpopen
584
Tim Peterse718f612004-10-12 21:51:32 +0000585
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586 def _execute_child(self, args, executable, preexec_fn, close_fds,
587 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200588 startupinfo, creationflags, shell, to_close,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 p2cread, p2cwrite,
590 c2pread, c2pwrite,
591 errread, errwrite):
592 """Execute program (MS Windows version)"""
593
Peter Astrandc26516b2005-02-21 08:13:02 +0000594 if not isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 args = list2cmdline(args)
596
Peter Astrandc1d65362004-11-07 14:30:34 +0000597 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000598 if startupinfo is None:
Georg Brandlad624892006-06-04 22:15:37 +0000599 startupinfo = STARTUPINFO()
600 if None not in (p2cread, c2pwrite, errwrite):
Brian Curtina2936cf2010-04-24 15:40:11 +0000601 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000602 startupinfo.hStdInput = p2cread
603 startupinfo.hStdOutput = c2pwrite
604 startupinfo.hStdError = errwrite
605
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 if shell:
Brian Curtina2936cf2010-04-24 15:40:11 +0000607 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
608 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden8e4756c2010-08-12 11:00:35 +0000610 args = '{} /c "{}"'.format (comspec, args)
611 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000612 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 # Win9x, or using command.com on NT. We need to
614 # use the w9xpopen intermediate program. For more
615 # information, see KB Q150956
616 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
617 w9xpopen = self._find_w9xpopen()
618 args = '"%s" %s' % (w9xpopen, args)
619 # Not passing CREATE_NEW_CONSOLE has been known to
620 # cause random failures on win9x. Specifically a
621 # dialog: "Your program accessed mem currently in
622 # use at xxx" and a hopeful warning about the
623 # stability of your system. Cost is Ctrl+C wont
624 # kill children.
Brian Curtina2936cf2010-04-24 15:40:11 +0000625 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200627 def _close_in_parent(fd):
628 fd.Close()
629 to_close.remove(fd)
630
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 # Start the process
632 try:
Brian Curtina2936cf2010-04-24 15:40:11 +0000633 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000634 # no special security
635 None, None,
Peter Astrand81a191b2007-05-26 22:18:20 +0000636 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000637 creationflags,
638 env,
639 cwd,
640 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 except pywintypes.error, e:
642 # Translate pywintypes.error to WindowsError, which is
643 # a subclass of OSError. FIXME: We should really
Ezio Melottic2077b02011-03-16 12:34:31 +0200644 # translate errno using _sys_errlist (or similar), but
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 # how can this be done from Python?
646 raise WindowsError(*e.args)
Tim Golden431774f2010-08-08 11:17:56 +0000647 finally:
648 # Child is launched. Close the parent's copy of those pipe
649 # handles that only the child should have open. You need
650 # to make sure that no handles to the write end of the
651 # output pipe are maintained in this process or else the
652 # pipe will not close when the child process exits and the
653 # ReadFile will hang.
654 if p2cread is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200655 _close_in_parent(p2cread)
Tim Golden431774f2010-08-08 11:17:56 +0000656 if c2pwrite is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200657 _close_in_parent(c2pwrite)
Tim Golden431774f2010-08-08 11:17:56 +0000658 if errwrite is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200659 _close_in_parent(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660
661 # Retain the process handle, but close the thread handle
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000662 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 self._handle = hp
664 self.pid = pid
665 ht.Close()
666
Brett Cannon42a0ba72010-05-14 00:21:48 +0000667 def _internal_poll(self, _deadstate=None,
Victor Stinner2b271f72010-05-14 21:52:26 +0000668 _WaitForSingleObject=_subprocess.WaitForSingleObject,
669 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
670 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 """Check if child process has terminated. Returns returncode
Brett Cannon42a0ba72010-05-14 00:21:48 +0000672 attribute.
673
674 This method is called by __del__, so it can only refer to objects
675 in its local scope.
676
677 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000678 if self.returncode is None:
Brett Cannon42a0ba72010-05-14 00:21:48 +0000679 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
680 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 return self.returncode
682
683
684 def wait(self):
685 """Wait for child process to terminate. Returns returncode
686 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000687 if self.returncode is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000688 _subprocess.WaitForSingleObject(self._handle,
689 _subprocess.INFINITE)
690 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000691 return self.returncode
692
693
694 def _readerthread(self, fh, buffer):
695 buffer.append(fh.read())
696
697
Peter Astrand23109f02005-03-03 20:28:59 +0000698 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 stdout = None # Return
700 stderr = None # Return
701
702 if self.stdout:
703 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000704 stdout_thread = threading.Thread(target=self._readerthread,
705 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 stdout_thread.setDaemon(True)
707 stdout_thread.start()
708 if self.stderr:
709 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000710 stderr_thread = threading.Thread(target=self._readerthread,
711 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000712 stderr_thread.setDaemon(True)
713 stderr_thread.start()
714
715 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000716 if input is not None:
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200717 try:
718 self.stdin.write(input)
719 except IOError as e:
Victor Stinnerc3828072014-07-29 00:04:54 +0200720 if e.errno == errno.EPIPE:
721 # communicate() should ignore broken pipe error
722 pass
Victor Stinnere5bdad22017-06-08 18:34:30 +0200723 elif e.errno == errno.EINVAL:
724 # bpo-19612, bpo-30418: On Windows, stdin.write()
725 # fails with EINVAL if the child process exited or
726 # if the child process is still running but closed
727 # the pipe.
Victor Stinnerc3828072014-07-29 00:04:54 +0200728 pass
729 else:
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200730 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 self.stdin.close()
732
733 if self.stdout:
734 stdout_thread.join()
735 if self.stderr:
736 stderr_thread.join()
737
738 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000739 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000741 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 stderr = stderr[0]
743
744 # Translate newlines, if requested. We cannot let the file
745 # object do the translation: It is based on stdio, which is
746 # impossible to combine with select (unless forcing no
747 # buffering).
Neal Norwitza6d01ce2006-05-02 06:23:22 +0000748 if self.universal_newlines and hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000749 if stdout:
750 stdout = self._translate_newlines(stdout)
751 if stderr:
752 stderr = self._translate_newlines(stderr)
753
754 self.wait()
755 return (stdout, stderr)
756
Christian Heimese74c8f22008-04-19 02:23:57 +0000757 def send_signal(self, sig):
758 """Send a signal to the process
759 """
760 if sig == signal.SIGTERM:
761 self.terminate()
Brian Curtine5aa8862010-04-02 23:26:06 +0000762 elif sig == signal.CTRL_C_EVENT:
763 os.kill(self.pid, signal.CTRL_C_EVENT)
764 elif sig == signal.CTRL_BREAK_EVENT:
765 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimese74c8f22008-04-19 02:23:57 +0000766 else:
Brian Curtine80513c2010-09-07 13:27:20 +0000767 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimese74c8f22008-04-19 02:23:57 +0000768
769 def terminate(self):
770 """Terminates the process
771 """
Antoine Pitrouf60845b2012-03-11 19:29:12 +0100772 try:
773 _subprocess.TerminateProcess(self._handle, 1)
774 except OSError as e:
775 # ERROR_ACCESS_DENIED (winerror 5) is received when the
776 # process already died.
777 if e.winerror != 5:
778 raise
779 rc = _subprocess.GetExitCodeProcess(self._handle)
780 if rc == _subprocess.STILL_ACTIVE:
781 raise
782 self.returncode = rc
Christian Heimese74c8f22008-04-19 02:23:57 +0000783
784 kill = terminate
785
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786 else:
787 #
788 # POSIX methods
789 #
790 def _get_handles(self, stdin, stdout, stderr):
Amaury Forgeot d'Arc8318afa2009-07-10 16:47:42 +0000791 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
793 """
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200794 to_close = set()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000795 p2cread, p2cwrite = None, None
796 c2pread, c2pwrite = None, None
797 errread, errwrite = None, None
798
Peter Astrandd38ddf42005-02-10 08:32:50 +0000799 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 pass
801 elif stdin == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200802 p2cread, p2cwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200803 to_close.update((p2cread, p2cwrite))
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200804 elif isinstance(stdin, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 p2cread = stdin
806 else:
807 # Assuming file-like object
808 p2cread = stdin.fileno()
809
Peter Astrandd38ddf42005-02-10 08:32:50 +0000810 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 pass
812 elif stdout == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200813 c2pread, c2pwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200814 to_close.update((c2pread, c2pwrite))
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200815 elif isinstance(stdout, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 c2pwrite = stdout
817 else:
818 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000819 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820
Peter Astrandd38ddf42005-02-10 08:32:50 +0000821 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000822 pass
823 elif stderr == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200824 errread, errwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200825 to_close.update((errread, errwrite))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 elif stderr == STDOUT:
Martin Panter1edccfa2016-05-13 01:54:44 +0000827 if c2pwrite is not None:
828 errwrite = c2pwrite
829 else: # child's stdout is not set, use parent's stdout
830 errwrite = sys.__stdout__.fileno()
Serhiy Storchaka994f04d2016-12-27 15:09:36 +0200831 elif isinstance(stderr, (int, long)):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 errwrite = stderr
833 else:
834 # Assuming file-like object
835 errwrite = stderr.fileno()
836
837 return (p2cread, p2cwrite,
838 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200839 errread, errwrite), to_close
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840
841
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000842 def _set_cloexec_flag(self, fd, cloexec=True):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 try:
844 cloexec_flag = fcntl.FD_CLOEXEC
845 except AttributeError:
846 cloexec_flag = 1
847
848 old = fcntl.fcntl(fd, fcntl.F_GETFD)
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000849 if cloexec:
850 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
851 else:
852 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853
854
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200855 def pipe_cloexec(self):
856 """Create a pipe with FDs set CLOEXEC."""
857 # Pipes' FDs are set CLOEXEC by default because we don't want them
858 # to be inherited by other subprocesses: the CLOEXEC flag is removed
859 # from the child's FDs by _dup2(), between fork() and exec().
860 # This is not atomic: we would need the pipe2() syscall for that.
861 r, w = os.pipe()
862 self._set_cloexec_flag(r)
863 self._set_cloexec_flag(w)
864 return r, w
865
866
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867 def _close_fds(self, but):
Amaury Forgeot d'Arc5fe420e2009-06-18 22:32:50 +0000868 if hasattr(os, 'closerange'):
869 os.closerange(3, but)
870 os.closerange(but + 1, MAXFD)
871 else:
872 for i in xrange(3, MAXFD):
873 if i == but:
874 continue
875 try:
876 os.close(i)
877 except:
878 pass
Tim Peterse718f612004-10-12 21:51:32 +0000879
880
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 def _execute_child(self, args, executable, preexec_fn, close_fds,
882 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200883 startupinfo, creationflags, shell, to_close,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884 p2cread, p2cwrite,
885 c2pread, c2pwrite,
886 errread, errwrite):
887 """Execute program (POSIX version)"""
888
Peter Astrandc26516b2005-02-21 08:13:02 +0000889 if isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 args = [args]
Georg Brandl6c0e1e82006-10-29 09:05:04 +0000891 else:
892 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893
894 if shell:
895 args = ["/bin/sh", "-c"] + args
Stefan Krahe9a6a7d2010-07-19 14:41:08 +0000896 if executable:
897 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 executable = args[0]
901
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200902 def _close_in_parent(fd):
903 os.close(fd)
904 to_close.remove(fd)
905
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000906 # For transferring possible exec failure from child to parent
907 # The first char specifies the exception type: 0 means
908 # OSError, 1 means some other error.
Charles-François Natali2a34eb32011-08-25 21:20:54 +0200909 errpipe_read, errpipe_write = self.pipe_cloexec()
Gregory P. Smith87d49792008-01-19 20:57:59 +0000910 try:
Gregory P. Smith92ffc632008-01-19 22:23:56 +0000911 try:
Facundo Batista8c826b72009-06-19 18:02:28 +0000912 gc_was_enabled = gc.isenabled()
913 # Disable gc to avoid bug where gc -> file_dealloc ->
914 # write to stderr -> hang. http://bugs.python.org/issue1336
915 gc.disable()
916 try:
917 self.pid = os.fork()
Georg Brandl3e8b8692009-07-16 21:47:51 +0000918 except:
Facundo Batista8c826b72009-06-19 18:02:28 +0000919 if gc_was_enabled:
920 gc.enable()
Georg Brandl3e8b8692009-07-16 21:47:51 +0000921 raise
Facundo Batista8c826b72009-06-19 18:02:28 +0000922 self._child_created = True
923 if self.pid == 0:
924 # Child
925 try:
926 # Close parent's pipe ends
927 if p2cwrite is not None:
928 os.close(p2cwrite)
929 if c2pread is not None:
930 os.close(c2pread)
931 if errread is not None:
932 os.close(errread)
933 os.close(errpipe_read)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934
Ross Lagerwalld8e39012011-07-27 18:54:53 +0200935 # When duping fds, if there arises a situation
936 # where one of the fds is either 0, 1 or 2, it
937 # is possible that it is overwritten (#12607).
938 if c2pwrite == 0:
939 c2pwrite = os.dup(c2pwrite)
940 if errwrite == 0 or errwrite == 1:
941 errwrite = os.dup(errwrite)
942
Facundo Batista8c826b72009-06-19 18:02:28 +0000943 # Dup fds for child
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000944 def _dup2(a, b):
945 # dup2() removes the CLOEXEC flag but
946 # we must do it ourselves if dup2()
947 # would be a no-op (issue #10806).
948 if a == b:
949 self._set_cloexec_flag(a, False)
950 elif a is not None:
951 os.dup2(a, b)
952 _dup2(p2cread, 0)
953 _dup2(c2pwrite, 1)
954 _dup2(errwrite, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955
Antoine Pitrou91ce0d92011-01-03 18:45:09 +0000956 # Close pipe fds. Make sure we don't close the
957 # same fd more than once, or standard fds.
958 closed = { None }
959 for fd in [p2cread, c2pwrite, errwrite]:
960 if fd not in closed and fd > 2:
961 os.close(fd)
962 closed.add(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000963
Facundo Batista8c826b72009-06-19 18:02:28 +0000964 if cwd is not None:
965 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Facundo Batista8c826b72009-06-19 18:02:28 +0000967 if preexec_fn:
968 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969
Charles-François Natali4c533142013-08-25 18:22:49 +0200970 # Close all other fds, if asked for - after
971 # preexec_fn(), which may open FDs.
972 if close_fds:
973 self._close_fds(but=errpipe_write)
974
Facundo Batista8c826b72009-06-19 18:02:28 +0000975 if env is None:
976 os.execvp(executable, args)
977 else:
978 os.execvpe(executable, args, env)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979
Facundo Batista8c826b72009-06-19 18:02:28 +0000980 except:
981 exc_type, exc_value, tb = sys.exc_info()
982 # Save the traceback and attach it to the exception object
983 exc_lines = traceback.format_exception(exc_type,
984 exc_value,
985 tb)
986 exc_value.child_traceback = ''.join(exc_lines)
987 os.write(errpipe_write, pickle.dumps(exc_value))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988
Facundo Batista8c826b72009-06-19 18:02:28 +0000989 # This exitcode won't be reported to applications, so it
990 # really doesn't matter what we return.
991 os._exit(255)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992
Facundo Batista8c826b72009-06-19 18:02:28 +0000993 # Parent
994 if gc_was_enabled:
995 gc.enable()
996 finally:
997 # be sure the FD is closed no matter what
998 os.close(errpipe_write)
999
Facundo Batista8c826b72009-06-19 18:02:28 +00001000 # Wait for exec to fail or succeed; possibly raising exception
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001001 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)253c0bf2016-05-28 19:24:14 +00001002 pickle_bits = []
Gregory P. Smith0d207fd2016-01-11 13:56:42 -08001003 while data:
1004 pickle_bits.append(data)
1005 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
1006 data = "".join(pickle_bits)
Facundo Batista8c826b72009-06-19 18:02:28 +00001007 finally:
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001008 if p2cread is not None and p2cwrite is not None:
1009 _close_in_parent(p2cread)
1010 if c2pwrite is not None and c2pread is not None:
1011 _close_in_parent(c2pwrite)
1012 if errwrite is not None and errread is not None:
1013 _close_in_parent(errwrite)
1014
Facundo Batista8c826b72009-06-19 18:02:28 +00001015 # be sure the FD is closed no matter what
1016 os.close(errpipe_read)
1017
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 if data != "":
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001019 try:
1020 _eintr_retry_call(os.waitpid, self.pid, 0)
1021 except OSError as e:
1022 if e.errno != errno.ECHILD:
1023 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024 child_exception = pickle.loads(data)
1025 raise child_exception
1026
1027
Brett Cannon42a0ba72010-05-14 00:21:48 +00001028 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1029 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08001030 _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED,
1031 _WSTOPSIG=os.WSTOPSIG):
Brett Cannon42a0ba72010-05-14 00:21:48 +00001032 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka30615852014-02-10 19:19:53 +02001033 # refer to anything outside of its local scope.
Brett Cannon42a0ba72010-05-14 00:21:48 +00001034 if _WIFSIGNALED(sts):
1035 self.returncode = -_WTERMSIG(sts)
1036 elif _WIFEXITED(sts):
1037 self.returncode = _WEXITSTATUS(sts)
Gregory P. Smithf0739cb2017-01-22 22:38:28 -08001038 elif _WIFSTOPPED(sts):
1039 self.returncode = -_WSTOPSIG(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001040 else:
1041 # Should never happen
1042 raise RuntimeError("Unknown child exit status!")
1043
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044
Brett Cannon42a0ba72010-05-14 00:21:48 +00001045 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov332562f2012-12-24 20:09:27 +02001046 _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 """Check if child process has terminated. Returns returncode
Brett Cannon42a0ba72010-05-14 00:21:48 +00001048 attribute.
1049
1050 This method is called by __del__, so it cannot reference anything
1051 outside of the local scope (nor can any methods it calls).
1052
1053 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001054 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055 try:
Brett Cannon42a0ba72010-05-14 00:21:48 +00001056 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057 if pid == self.pid:
1058 self._handle_exitstatus(sts)
Gregory P. Smith0798cbc2012-09-29 12:02:48 -07001059 except _os_error as e:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +00001060 if _deadstate is not None:
1061 self.returncode = _deadstate
Andrew Svetlov332562f2012-12-24 20:09:27 +02001062 if e.errno == _ECHILD:
Gregory P. Smith0798cbc2012-09-29 12:02:48 -07001063 # This happens if SIGCLD is set to be ignored or
1064 # waiting for child processes has otherwise been
1065 # disabled for our process. This child is dead, we
1066 # can't get the status.
1067 # http://bugs.python.org/issue15756
1068 self.returncode = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 return self.returncode
1070
1071
1072 def wait(self):
1073 """Wait for child process to terminate. Returns returncode
1074 attribute."""
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001075 while self.returncode is None:
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001076 try:
1077 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1078 except OSError as e:
1079 if e.errno != errno.ECHILD:
1080 raise
1081 # This happens if SIGCLD is set to be ignored or waiting
1082 # for child processes has otherwise been disabled for our
1083 # process. This child is dead, we can't get the status.
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001084 pid = self.pid
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001085 sts = 0
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001086 # Check the pid and loop as waitpid has been known to return
1087 # 0 even without WNOHANG in odd situations. issue14396.
1088 if pid == self.pid:
1089 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 return self.returncode
1091
1092
Peter Astrand23109f02005-03-03 20:28:59 +00001093 def _communicate(self, input):
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001094 if self.stdin:
1095 # Flush stdio buffer. This might block, if the user has
1096 # been writing to .stdin in an uncontrolled fashion.
1097 self.stdin.flush()
1098 if not input:
1099 self.stdin.close()
1100
1101 if _has_poll:
1102 stdout, stderr = self._communicate_with_poll(input)
1103 else:
1104 stdout, stderr = self._communicate_with_select(input)
1105
1106 # All data exchanged. Translate lists into strings.
1107 if stdout is not None:
1108 stdout = ''.join(stdout)
1109 if stderr is not None:
1110 stderr = ''.join(stderr)
1111
1112 # Translate newlines, if requested. We cannot let the file
1113 # object do the translation: It is based on stdio, which is
1114 # impossible to combine with select (unless forcing no
1115 # buffering).
1116 if self.universal_newlines and hasattr(file, 'newlines'):
1117 if stdout:
1118 stdout = self._translate_newlines(stdout)
1119 if stderr:
1120 stderr = self._translate_newlines(stderr)
1121
1122 self.wait()
1123 return (stdout, stderr)
1124
1125
1126 def _communicate_with_poll(self, input):
1127 stdout = None # Return
1128 stderr = None # Return
1129 fd2file = {}
1130 fd2output = {}
1131
1132 poller = select.poll()
1133 def register_and_append(file_obj, eventmask):
1134 poller.register(file_obj.fileno(), eventmask)
1135 fd2file[file_obj.fileno()] = file_obj
1136
1137 def close_unregister_and_remove(fd):
1138 poller.unregister(fd)
1139 fd2file[fd].close()
1140 fd2file.pop(fd)
1141
1142 if self.stdin and input:
1143 register_and_append(self.stdin, select.POLLOUT)
1144
1145 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1146 if self.stdout:
1147 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1148 fd2output[self.stdout.fileno()] = stdout = []
1149 if self.stderr:
1150 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1151 fd2output[self.stderr.fileno()] = stderr = []
1152
1153 input_offset = 0
1154 while fd2file:
1155 try:
1156 ready = poller.poll()
1157 except select.error, e:
1158 if e.args[0] == errno.EINTR:
1159 continue
1160 raise
1161
1162 for fd, mode in ready:
1163 if mode & select.POLLOUT:
1164 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001165 try:
1166 input_offset += os.write(fd, chunk)
1167 except OSError as e:
1168 if e.errno == errno.EPIPE:
1169 close_unregister_and_remove(fd)
1170 else:
1171 raise
1172 else:
1173 if input_offset >= len(input):
1174 close_unregister_and_remove(fd)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001175 elif mode & select_POLLIN_POLLPRI:
1176 data = os.read(fd, 4096)
1177 if not data:
1178 close_unregister_and_remove(fd)
1179 fd2output[fd].append(data)
1180 else:
1181 # Ignore hang up or errors.
1182 close_unregister_and_remove(fd)
1183
1184 return (stdout, stderr)
1185
1186
1187 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001188 read_set = []
1189 write_set = []
1190 stdout = None # Return
1191 stderr = None # Return
1192
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001193 if self.stdin and input:
1194 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001195 if self.stdout:
1196 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001197 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001198 if self.stderr:
1199 read_set.append(self.stderr)
1200 stderr = []
1201
Peter Astrand1812f8c2007-01-07 14:34:16 +00001202 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001203 while read_set or write_set:
Gregory P. Smithf4140642008-07-06 07:16:40 +00001204 try:
1205 rlist, wlist, xlist = select.select(read_set, write_set, [])
1206 except select.error, e:
1207 if e.args[0] == errno.EINTR:
1208 continue
1209 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001210
1211 if self.stdin in wlist:
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001212 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001213 try:
1214 bytes_written = os.write(self.stdin.fileno(), chunk)
1215 except OSError as e:
1216 if e.errno == errno.EPIPE:
1217 self.stdin.close()
1218 write_set.remove(self.stdin)
1219 else:
1220 raise
1221 else:
1222 input_offset += bytes_written
1223 if input_offset >= len(input):
1224 self.stdin.close()
1225 write_set.remove(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001226
1227 if self.stdout in rlist:
1228 data = os.read(self.stdout.fileno(), 1024)
1229 if data == "":
1230 self.stdout.close()
1231 read_set.remove(self.stdout)
1232 stdout.append(data)
1233
1234 if self.stderr in rlist:
1235 data = os.read(self.stderr.fileno(), 1024)
1236 if data == "":
1237 self.stderr.close()
1238 read_set.remove(self.stderr)
1239 stderr.append(data)
1240
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001241 return (stdout, stderr)
1242
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001243
Christian Heimese74c8f22008-04-19 02:23:57 +00001244 def send_signal(self, sig):
1245 """Send a signal to the process
1246 """
1247 os.kill(self.pid, sig)
1248
1249 def terminate(self):
1250 """Terminate the process with SIGTERM
1251 """
1252 self.send_signal(signal.SIGTERM)
1253
1254 def kill(self):
1255 """Kill the process with SIGKILL
1256 """
1257 self.send_signal(signal.SIGKILL)
1258
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001259
1260def _demo_posix():
1261 #
1262 # Example 1: Simple redirection: Get process list
1263 #
1264 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1265 print "Process list:"
1266 print plist
1267
1268 #
1269 # Example 2: Change uid before executing child
1270 #
1271 if os.getuid() == 0:
1272 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1273 p.wait()
1274
1275 #
1276 # Example 3: Connecting several subprocesses
1277 #
1278 print "Looking for 'hda'..."
1279 p1 = Popen(["dmesg"], stdout=PIPE)
1280 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1281 print repr(p2.communicate()[0])
1282
1283 #
1284 # Example 4: Catch execution error
1285 #
1286 print
1287 print "Trying a weird file..."
1288 try:
1289 print Popen(["/this/path/does/not/exist"]).communicate()
1290 except OSError, e:
1291 if e.errno == errno.ENOENT:
1292 print "The file didn't exist. I thought so..."
1293 print "Child traceback:"
1294 print e.child_traceback
1295 else:
1296 print "Error", e.errno
1297 else:
1298 print >>sys.stderr, "Gosh. No error."
1299
1300
1301def _demo_windows():
1302 #
1303 # Example 1: Connecting several subprocesses
1304 #
1305 print "Looking for 'PROMPT' in set output..."
1306 p1 = Popen("set", stdout=PIPE, shell=True)
1307 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1308 print repr(p2.communicate()[0])
1309
1310 #
1311 # Example 2: Simple execution of program
1312 #
1313 print "Executing calc..."
1314 p = Popen("calc")
1315 p.wait()
1316
1317
1318if __name__ == "__main__":
1319 if mswindows:
1320 _demo_windows()
1321 else:
1322 _demo_posix()