blob: 7cfe5df30d7f8f5f96e56fe658177d9f3785b007 [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
28class Popen(args, bufsize=0, executable=None,
29 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
59bufsize, if given, has the same meaning as the corresponding argument
60to the built-in open() function: 0 means unbuffered, 1 means line
61buffered, any other positive value means use a buffer of
62(approximately) that size. A negative bufsize means to use the system
63default, which usually means fully buffered. The default value for
64bufsize is 0 (unbuffered).
65
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
107If universal_newlines is true, the file objects stdout and stderr are
108opened as a text files, but lines may be terminated by any of '\n',
Gregory P. Smithf5604852010-12-13 06:45:02 +0000109the Unix end-of-line convention, '\r', the old Macintosh convention or
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110'\r\n', the Windows convention. All of these external representations
Gregory P. Smith1f8a40b2013-03-20 18:32:03 -0700111are seen as '\n' by the Python program. Also, the newlines attribute
112of the file objects stdout, stdin and stderr are not updated by the
113communicate() method.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114
115The startupinfo and creationflags, if given, will be passed to the
116underlying CreateProcess() function. They can specify things such as
117appearance of the main window and priority for the new process.
118(Windows only)
119
120
Georg Brandlf9734072008-12-07 15:30:06 +0000121This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122
Peter Astrand5f5e1412004-12-05 20:15:36 +0000123call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124 Run command with arguments. Wait for command to complete, then
125 return the returncode attribute.
126
127 The arguments are the same as for the Popen constructor. Example:
128
Florent Xicluna4886d242010-03-08 13:27:26 +0000129 >>> retcode = subprocess.call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000130
Peter Astrand454f7672005-01-01 09:36:35 +0000131check_call(*popenargs, **kwargs):
132 Run command with arguments. Wait for command to complete. If the
133 exit code was zero then return, otherwise raise
134 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000135 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000136
137 The arguments are the same as for the Popen constructor. Example:
138
Florent Xicluna4886d242010-03-08 13:27:26 +0000139 >>> subprocess.check_call(["ls", "-l"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000140 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141
Brett Cannona23810f2008-05-26 19:04:21 +0000142getstatusoutput(cmd):
143 Return (status, output) of executing cmd in a shell.
144
145 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
146 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
147 returned output will contain output or error messages. A trailing newline
148 is stripped from the output. The exit status for the command can be
149 interpreted according to the rules for the C function wait(). Example:
150
Brett Cannona23810f2008-05-26 19:04:21 +0000151 >>> subprocess.getstatusoutput('ls /bin/ls')
152 (0, '/bin/ls')
153 >>> subprocess.getstatusoutput('cat /bin/junk')
154 (256, 'cat: /bin/junk: No such file or directory')
155 >>> subprocess.getstatusoutput('/bin/junk')
156 (256, 'sh: /bin/junk: not found')
157
158getoutput(cmd):
159 Return output (stdout or stderr) of executing cmd in a shell.
160
161 Like getstatusoutput(), except the exit status is ignored and the return
162 value is a string containing the command's output. Example:
163
Brett Cannona23810f2008-05-26 19:04:21 +0000164 >>> subprocess.getoutput('ls /bin/ls')
165 '/bin/ls'
166
Georg Brandlf9734072008-12-07 15:30:06 +0000167check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000168 Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000169
Georg Brandl2708f3a2009-12-20 14:38:23 +0000170 If the exit code was non-zero it raises a CalledProcessError. The
171 CalledProcessError object will have the return code in the returncode
172 attribute and output in the output attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000173
Georg Brandl2708f3a2009-12-20 14:38:23 +0000174 The arguments are the same as for the Popen constructor. Example:
Georg Brandlf9734072008-12-07 15:30:06 +0000175
Georg Brandl2708f3a2009-12-20 14:38:23 +0000176 >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandlf9734072008-12-07 15:30:06 +0000177
Brett Cannona23810f2008-05-26 19:04:21 +0000178
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000179Exceptions
180----------
181Exceptions raised in the child process, before the new program has
182started to execute, will be re-raised in the parent. Additionally,
183the exception object will have one extra attribute called
184'child_traceback', which is a string containing traceback information
185from the childs point of view.
186
187The most common exception raised is OSError. This occurs, for
188example, when trying to execute a non-existent file. Applications
189should prepare for OSErrors.
190
191A ValueError will be raised if Popen is called with invalid arguments.
192
Georg Brandlf9734072008-12-07 15:30:06 +0000193check_call() and check_output() will raise CalledProcessError, if the
194called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000195
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000196
197Security
198--------
199Unlike some other popen functions, this implementation will never call
200/bin/sh implicitly. This means that all characters, including shell
201metacharacters, can safely be passed to child processes.
202
203
204Popen objects
205=============
206Instances of the Popen class have the following methods:
207
208poll()
209 Check if child process has terminated. Returns returncode
210 attribute.
211
212wait()
213 Wait for child process to terminate. Returns returncode attribute.
214
215communicate(input=None)
216 Interact with process: Send data to stdin. Read data from stdout
217 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000218 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 sent to the child process, or None, if no data should be sent to
220 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000221
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 communicate() returns a tuple (stdout, stderr).
223
224 Note: The data read is buffered in memory, so do not use this
225 method if the data size is large or unlimited.
226
227The following attributes are also available:
228
229stdin
230 If the stdin argument is PIPE, this attribute is a file object
231 that provides input to the child process. Otherwise, it is None.
232
233stdout
234 If the stdout argument is PIPE, this attribute is a file object
235 that provides output from the child process. Otherwise, it is
236 None.
237
238stderr
239 If the stderr argument is PIPE, this attribute is file object that
240 provides error output from the child process. Otherwise, it is
241 None.
242
243pid
244 The process ID of the child process.
245
246returncode
247 The child return code. A None value indicates that the process
248 hasn't terminated yet. A negative value -N indicates that the
Gregory P. Smithf5604852010-12-13 06:45:02 +0000249 child was terminated by signal N (POSIX only).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250
251
252Replacing older functions with the subprocess module
253====================================================
254In this section, "a ==> b" means that b can be used as a replacement
255for a.
256
257Note: All functions in this section fail (more or less) silently if
258the executed program cannot be found; this module raises an OSError
259exception.
260
261In the following examples, we assume that the subprocess module is
262imported with "from subprocess import *".
263
264
265Replacing /bin/sh shell backquote
266---------------------------------
267output=`mycmd myarg`
268==>
269output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
270
271
272Replacing shell pipe line
273-------------------------
274output=`dmesg | grep hda`
275==>
276p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000277p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278output = p2.communicate()[0]
279
280
281Replacing os.system()
282---------------------
283sts = os.system("mycmd" + " myarg")
284==>
285p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000286pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287
288Note:
289
290* Calling the program through the shell is usually not required.
291
292* It's easier to look at the returncode attribute than the
293 exitstatus.
294
295A more real-world example would look like this:
296
297try:
298 retcode = call("mycmd" + " myarg", shell=True)
299 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000300 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000302 print("Child returned", retcode, file=sys.stderr)
303except OSError as e:
304 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305
306
307Replacing os.spawn*
308-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000309P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310
311pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
312==>
313pid = Popen(["/bin/mycmd", "myarg"]).pid
314
315
316P_WAIT example:
317
318retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
319==>
320retcode = call(["/bin/mycmd", "myarg"])
321
322
Tim Peterse718f612004-10-12 21:51:32 +0000323Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324
325os.spawnvp(os.P_NOWAIT, path, args)
326==>
327Popen([path] + args[1:])
328
329
Tim Peterse718f612004-10-12 21:51:32 +0000330Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331
332os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
333==>
334Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335"""
336
337import sys
338mswindows = (sys.platform == "win32")
339
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000340import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000342import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000343import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000344import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000345import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000346import warnings
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200347import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000348
Peter Astrand454f7672005-01-01 09:36:35 +0000349# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000350class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000351 """This exception is raised when a process run by check_call() or
352 check_output() returns a non-zero exit status.
353 The exit status will be stored in the returncode attribute;
354 check_output() will also store the output in the output attribute.
355 """
356 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000357 self.returncode = returncode
358 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000359 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000360 def __str__(self):
361 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
362
Peter Astrand454f7672005-01-01 09:36:35 +0000363
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364if mswindows:
365 import threading
366 import msvcrt
Brian Curtin1ce6b582010-04-24 16:19:22 +0000367 import _subprocess
368 class STARTUPINFO:
369 dwFlags = 0
370 hStdInput = None
371 hStdOutput = None
372 hStdError = None
373 wShowWindow = 0
374 class pywintypes:
375 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376else:
377 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000378 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379 import fcntl
380 import pickle
381
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000382 try:
383 import _posixsubprocess
384 except ImportError:
385 _posixsubprocess = None
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000386 warnings.warn("The _posixsubprocess module is not being used. "
387 "Child process reliability may suffer if your "
388 "program uses threads.", RuntimeWarning)
389
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000390 # When select or poll has indicated that the file is writable,
391 # we can write up to _PIPE_BUF bytes without risk of blocking.
392 # POSIX defines PIPE_BUF as >= 512.
393 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
394
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000395 _FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1)
396
397 def _set_cloexec(fd, cloexec):
398 old = fcntl.fcntl(fd, fcntl.F_GETFD)
399 if cloexec:
400 fcntl.fcntl(fd, fcntl.F_SETFD, old | _FD_CLOEXEC)
401 else:
402 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~_FD_CLOEXEC)
403
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000404 if _posixsubprocess:
405 _create_pipe = _posixsubprocess.cloexec_pipe
406 else:
407 def _create_pipe():
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000408 fds = os.pipe()
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000409 _set_cloexec(fds[0], True)
410 _set_cloexec(fds[1], True)
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000411 return fds
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000412
Brett Cannona23810f2008-05-26 19:04:21 +0000413__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000414 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415
Brian Curtin1ce6b582010-04-24 16:19:22 +0000416if mswindows:
Brian Curtin08fd8d92011-04-29 16:11:30 -0500417 from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500418 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
419 STD_ERROR_HANDLE, SW_HIDE,
420 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Gregory P. Smith0ef3e392011-05-11 22:20:11 -0700421
Brian Curtin08fd8d92011-04-29 16:11:30 -0500422 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500423 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
424 "STD_ERROR_HANDLE", "SW_HIDE",
425 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426try:
427 MAXFD = os.sysconf("SC_OPEN_MAX")
428except:
429 MAXFD = 256
430
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200431# This lists holds Popen instances for which the underlying process had not
432# exited at the time its __del__ method got called: those processes are wait()ed
433# for synchronously from _cleanup() when a new Popen object is created, to avoid
434# zombie processes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435_active = []
436
437def _cleanup():
438 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000439 res = inst._internal_poll(_deadstate=sys.maxsize)
Charles-François Natali134a8ba2011-08-18 18:49:39 +0200440 if res is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000441 try:
442 _active.remove(inst)
443 except ValueError:
444 # This can happen if two threads create a new Popen instance.
445 # It's harmless that it was already removed, so ignore.
446 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447
448PIPE = -1
449STDOUT = -2
450
451
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000452def _eintr_retry_call(func, *args):
453 while True:
454 try:
455 return func(*args)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200456 except (OSError, IOError) as e:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000457 if e.errno == errno.EINTR:
458 continue
459 raise
460
461
Peter Astrand5f5e1412004-12-05 20:15:36 +0000462def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463 """Run command with arguments. Wait for command to complete, then
464 return the returncode attribute.
465
466 The arguments are the same as for the Popen constructor. Example:
467
468 retcode = call(["ls", "-l"])
469 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000470 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472
Peter Astrand454f7672005-01-01 09:36:35 +0000473def check_call(*popenargs, **kwargs):
474 """Run command with arguments. Wait for command to complete. If
475 the exit code was zero then return, otherwise raise
476 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000478
479 The arguments are the same as for the Popen constructor. Example:
480
481 check_call(["ls", "-l"])
482 """
483 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000484 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000485 cmd = kwargs.get("args")
486 if cmd is None:
487 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000488 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000489 return 0
490
491
492def check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000493 r"""Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000494
495 If the exit code was non-zero it raises a CalledProcessError. The
496 CalledProcessError object will have the return code in the returncode
497 attribute and output in the output attribute.
498
499 The arguments are the same as for the Popen constructor. Example:
500
501 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000502 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000503
504 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000505 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000506
507 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000508 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000509 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000510 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000511 """
512 if 'stdout' in kwargs:
513 raise ValueError('stdout argument not allowed, it will be overridden.')
514 process = Popen(*popenargs, stdout=PIPE, **kwargs)
515 output, unused_err = process.communicate()
516 retcode = process.poll()
517 if retcode:
518 cmd = kwargs.get("args")
519 if cmd is None:
520 cmd = popenargs[0]
521 raise CalledProcessError(retcode, cmd, output=output)
522 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000523
524
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525def list2cmdline(seq):
526 """
527 Translate a sequence of arguments into a command line
528 string, using the same rules as the MS C runtime:
529
530 1) Arguments are delimited by white space, which is either a
531 space or a tab.
532
533 2) A string surrounded by double quotation marks is
534 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000535 contained within. A quoted string can be embedded in an
536 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537
538 3) A double quotation mark preceded by a backslash is
539 interpreted as a literal double quotation mark.
540
541 4) Backslashes are interpreted literally, unless they
542 immediately precede a double quotation mark.
543
544 5) If backslashes immediately precede a double quotation mark,
545 every pair of backslashes is interpreted as a literal
546 backslash. If the number of backslashes is odd, the last
547 backslash escapes the next double quotation mark as
548 described in rule 3.
549 """
550
551 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000552 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
553 # or search http://msdn.microsoft.com for
554 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555 result = []
556 needquote = False
557 for arg in seq:
558 bs_buf = []
559
560 # Add a space to separate this argument from the others
561 if result:
562 result.append(' ')
563
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000564 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 if needquote:
566 result.append('"')
567
568 for c in arg:
569 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000570 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571 bs_buf.append(c)
572 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000573 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 result.append('\\' * len(bs_buf)*2)
575 bs_buf = []
576 result.append('\\"')
577 else:
578 # Normal char
579 if bs_buf:
580 result.extend(bs_buf)
581 bs_buf = []
582 result.append(c)
583
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 if bs_buf:
586 result.extend(bs_buf)
587
588 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000589 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 result.append('"')
591
592 return ''.join(result)
593
594
Brett Cannona23810f2008-05-26 19:04:21 +0000595# Various tools for executing commands and looking at their output and status.
596#
Gregory P. Smithf5604852010-12-13 06:45:02 +0000597# NB This only works (and is only relevant) for POSIX.
Brett Cannona23810f2008-05-26 19:04:21 +0000598
599def getstatusoutput(cmd):
600 """Return (status, output) of executing cmd in a shell.
601
602 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
603 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
604 returned output will contain output or error messages. A trailing newline
605 is stripped from the output. The exit status for the command can be
606 interpreted according to the rules for the C function wait(). Example:
607
608 >>> import subprocess
609 >>> subprocess.getstatusoutput('ls /bin/ls')
610 (0, '/bin/ls')
611 >>> subprocess.getstatusoutput('cat /bin/junk')
612 (256, 'cat: /bin/junk: No such file or directory')
613 >>> subprocess.getstatusoutput('/bin/junk')
614 (256, 'sh: /bin/junk: not found')
615 """
616 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
617 text = pipe.read()
618 sts = pipe.close()
619 if sts is None: sts = 0
620 if text[-1:] == '\n': text = text[:-1]
621 return sts, text
622
623
624def getoutput(cmd):
625 """Return output (stdout or stderr) of executing cmd in a shell.
626
627 Like getstatusoutput(), except the exit status is ignored and the return
628 value is a string containing the command's output. Example:
629
630 >>> import subprocess
631 >>> subprocess.getoutput('ls /bin/ls')
632 '/bin/ls'
633 """
634 return getstatusoutput(cmd)[1]
635
636
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000637_PLATFORM_DEFAULT_CLOSE_FDS = object()
Gregory P. Smithf5604852010-12-13 06:45:02 +0000638
639
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640class Popen(object):
641 def __init__(self, args, bufsize=0, executable=None,
642 stdin=None, stdout=None, stderr=None,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000643 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
644 shell=False, cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000645 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000646 restore_signals=True, start_new_session=False,
647 pass_fds=()):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 """Create new Popen instance."""
649 _cleanup()
650
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000652 if bufsize is None:
653 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000654 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000655 raise TypeError("bufsize must be an integer")
656
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000658 if preexec_fn is not None:
659 raise ValueError("preexec_fn is not supported on Windows "
660 "platforms")
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000661 any_stdio_set = (stdin is not None or stdout is not None or
662 stderr is not None)
663 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
664 if any_stdio_set:
665 close_fds = False
666 else:
667 close_fds = True
668 elif close_fds and any_stdio_set:
669 raise ValueError(
670 "close_fds is not supported on Windows platforms"
671 " if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 else:
673 # POSIX
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000674 if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
675 close_fds = True
676 if pass_fds and not close_fds:
677 warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
678 close_fds = True
Tim Peterse8374a52004-10-13 03:15:00 +0000679 if startupinfo is not None:
680 raise ValueError("startupinfo is only supported on Windows "
681 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000683 raise ValueError("creationflags is only supported on Windows "
684 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685
Tim Peterse718f612004-10-12 21:51:32 +0000686 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 self.stdout = None
688 self.stderr = None
689 self.pid = None
690 self.returncode = None
691 self.universal_newlines = universal_newlines
692
693 # Input and output objects. The general principle is like
694 # this:
695 #
696 # Parent Child
697 # ------ -----
698 # p2cwrite ---stdin---> p2cread
699 # c2pread <--stdout--- c2pwrite
700 # errread <--stderr--- errwrite
701 #
702 # On POSIX, the child objects are file descriptors. On
703 # Windows, these are Windows file handles. The parent objects
704 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000705 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000707
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000708 (p2cread, p2cwrite,
709 c2pread, c2pwrite,
710 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
711
Antoine Pitrouc9982322011-01-04 19:07:07 +0000712 # We wrap OS handles *before* launching the child, otherwise a
713 # quickly terminating child could make our fds unwrappable
714 # (see #8458).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000715
Thomas Wouterscf297e42007-02-23 15:07:44 +0000716 if mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000717 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000718 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000719 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000720 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000721 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000722 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000723
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000724 if p2cwrite != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000725 self.stdin = io.open(p2cwrite, 'wb', bufsize)
726 if self.universal_newlines:
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200727 self.stdin = io.TextIOWrapper(self.stdin, write_through=True)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000728 if c2pread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000729 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000731 self.stdout = io.TextIOWrapper(self.stdout)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000732 if errread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000733 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000735 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000736
Antoine Pitrouc9982322011-01-04 19:07:07 +0000737 try:
738 self._execute_child(args, executable, preexec_fn, close_fds,
739 pass_fds, cwd, env, universal_newlines,
740 startupinfo, creationflags, shell,
741 p2cread, p2cwrite,
742 c2pread, c2pwrite,
743 errread, errwrite,
744 restore_signals, start_new_session)
745 except:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800746 # Cleanup if the child failed starting.
747 for f in filter(None, (self.stdin, self.stdout, self.stderr)):
Antoine Pitrouc9982322011-01-04 19:07:07 +0000748 try:
749 f.close()
750 except EnvironmentError:
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800751 pass # Ignore EBADF or other errors.
752
753 # Make sure the child pipes are closed as well.
754 to_close = []
755 if stdin == PIPE:
756 to_close.append(p2cread)
757 if stdout == PIPE:
758 to_close.append(c2pwrite)
759 if stderr == PIPE:
760 to_close.append(errwrite)
761 for fd in to_close:
762 try:
763 os.close(fd)
764 except EnvironmentError:
Antoine Pitrouc9982322011-01-04 19:07:07 +0000765 pass
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800766
Antoine Pitrouc9982322011-01-04 19:07:07 +0000767 raise
768
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769
Guido van Rossum98297ee2007-11-06 21:34:58 +0000770 def _translate_newlines(self, data, encoding):
Andrew Svetlov82860712012-08-19 22:13:41 +0300771 data = data.decode(encoding)
772 return data.replace("\r\n", "\n").replace("\r", "\n")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773
Brian Curtin79cdb662010-12-03 02:46:02 +0000774 def __enter__(self):
775 return self
776
777 def __exit__(self, type, value, traceback):
778 if self.stdout:
779 self.stdout.close()
780 if self.stderr:
781 self.stderr.close()
782 if self.stdin:
783 self.stdin.close()
Gregory P. Smithc9557af2011-05-11 22:18:23 -0700784 # Wait for the process to terminate, to avoid zombies.
785 self.wait()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
Brett Cannon84df1e62010-05-14 00:33:40 +0000787 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Victor Stinner87b9bc32011-06-01 00:57:47 +0200788 # If __init__ hasn't had a chance to execute (e.g. if it
789 # was passed an undeclared keyword argument), we don't
790 # have a _child_created attribute at all.
791 if not getattr(self, '_child_created', False):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792 # We didn't get to successfully create a child process.
793 return
794 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000795 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000796 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000797 # Child is still running, keep us alive until we can wait on it.
798 _active.append(self)
799
800
Peter Astrand23109f02005-03-03 20:28:59 +0000801 def communicate(self, input=None):
802 """Interact with process: Send data to stdin. Read data from
803 stdout and stderr, until end-of-file is reached. Wait for
804 process to terminate. The optional input argument should be a
805 string to be sent to the child process, or None, if no data
806 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000807
Peter Astrand23109f02005-03-03 20:28:59 +0000808 communicate() returns a tuple (stdout, stderr)."""
809
810 # Optimization: If we are only using one pipe, or no pipe at
811 # all, using select() or threads is unnecessary.
812 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000813 stdout = None
814 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000815 if self.stdin:
816 if input:
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200817 try:
818 self.stdin.write(input)
819 except IOError as e:
820 if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
821 raise
Peter Astrand23109f02005-03-03 20:28:59 +0000822 self.stdin.close()
823 elif self.stdout:
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200824 stdout = _eintr_retry_call(self.stdout.read)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000825 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000826 elif self.stderr:
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200827 stderr = _eintr_retry_call(self.stderr.read)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000828 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000829 self.wait()
830 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000831
Peter Astrand23109f02005-03-03 20:28:59 +0000832 return self._communicate(input)
833
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000835 def poll(self):
836 return self._internal_poll()
837
838
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 if mswindows:
840 #
841 # Windows methods
842 #
843 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000844 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
846 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000847 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000848 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000849
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000850 p2cread, p2cwrite = -1, -1
851 c2pread, c2pwrite = -1, -1
852 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853
Peter Astrandd38ddf42005-02-10 08:32:50 +0000854 if stdin is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000855 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000856 if p2cread is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000857 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000858 elif stdin == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000859 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000860 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861 p2cread = msvcrt.get_osfhandle(stdin)
862 else:
863 # Assuming file-like object
864 p2cread = msvcrt.get_osfhandle(stdin.fileno())
865 p2cread = self._make_inheritable(p2cread)
866
Peter Astrandd38ddf42005-02-10 08:32:50 +0000867 if stdout is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000868 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000869 if c2pwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000870 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000871 elif stdout == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000872 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000873 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000874 c2pwrite = msvcrt.get_osfhandle(stdout)
875 else:
876 # Assuming file-like object
877 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
878 c2pwrite = self._make_inheritable(c2pwrite)
879
Peter Astrandd38ddf42005-02-10 08:32:50 +0000880 if stderr is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000881 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000882 if errwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000883 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000884 elif stderr == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000885 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886 elif stderr == STDOUT:
887 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000888 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 errwrite = msvcrt.get_osfhandle(stderr)
890 else:
891 # Assuming file-like object
892 errwrite = msvcrt.get_osfhandle(stderr.fileno())
893 errwrite = self._make_inheritable(errwrite)
894
895 return (p2cread, p2cwrite,
896 c2pread, c2pwrite,
897 errread, errwrite)
898
899
900 def _make_inheritable(self, handle):
901 """Return a duplicate of handle, which is inheritable"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000902 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
903 handle, _subprocess.GetCurrentProcess(), 0, 1,
904 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000905
906
907 def _find_w9xpopen(self):
908 """Find and return absolut path to w9xpopen.exe"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000909 w9xpopen = os.path.join(
910 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000911 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 if not os.path.exists(w9xpopen):
913 # Eeek - file-not-found - possibly an embedding
914 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000915 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
916 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000918 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
919 "needed for Popen to work with your "
920 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921 return w9xpopen
922
Tim Peterse718f612004-10-12 21:51:32 +0000923
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000925 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926 startupinfo, creationflags, shell,
927 p2cread, p2cwrite,
928 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000929 errread, errwrite,
930 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 """Execute program (MS Windows version)"""
932
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000933 assert not pass_fds, "pass_fds not supported on Windows."
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000934
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000935 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000936 args = list2cmdline(args)
937
Peter Astrandc1d65362004-11-07 14:30:34 +0000938 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000939 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000940 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +0000941 if -1 not in (p2cread, c2pwrite, errwrite):
Brian Curtin1ce6b582010-04-24 16:19:22 +0000942 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000943 startupinfo.hStdInput = p2cread
944 startupinfo.hStdOutput = c2pwrite
945 startupinfo.hStdError = errwrite
946
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947 if shell:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000948 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
949 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +0000951 args = '{} /c "{}"'.format (comspec, args)
Brian Curtin1ce6b582010-04-24 16:19:22 +0000952 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000953 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000954 # Win9x, or using command.com on NT. We need to
955 # use the w9xpopen intermediate program. For more
956 # information, see KB Q150956
957 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
958 w9xpopen = self._find_w9xpopen()
959 args = '"%s" %s' % (w9xpopen, args)
960 # Not passing CREATE_NEW_CONSOLE has been known to
961 # cause random failures on win9x. Specifically a
962 # dialog: "Your program accessed mem currently in
963 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000964 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965 # kill children.
Brian Curtin1ce6b582010-04-24 16:19:22 +0000966 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000967
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 # Start the process
969 try:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000970 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000971 # no special security
972 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000973 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000974 creationflags,
975 env,
976 cwd,
977 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000978 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979 # Translate pywintypes.error to WindowsError, which is
980 # a subclass of OSError. FIXME: We should really
Ezio Melotti13925002011-03-16 11:05:33 +0200981 # translate errno using _sys_errlist (or similar), but
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 # how can this be done from Python?
983 raise WindowsError(*e.args)
Tim Goldenad537f22010-08-08 11:18:16 +0000984 finally:
985 # Child is launched. Close the parent's copy of those pipe
986 # handles that only the child should have open. You need
987 # to make sure that no handles to the write end of the
988 # output pipe are maintained in this process or else the
989 # pipe will not close when the child process exits and the
990 # ReadFile will hang.
991 if p2cread != -1:
992 p2cread.Close()
993 if c2pwrite != -1:
994 c2pwrite.Close()
995 if errwrite != -1:
996 errwrite.Close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997
998 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000999 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 self._handle = hp
1001 self.pid = pid
1002 ht.Close()
1003
Brett Cannon84df1e62010-05-14 00:33:40 +00001004 def _internal_poll(self, _deadstate=None,
Victor Stinnerc807a612010-05-14 21:53:45 +00001005 _WaitForSingleObject=_subprocess.WaitForSingleObject,
1006 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
1007 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001009 attribute.
1010
1011 This method is called by __del__, so it can only refer to objects
1012 in its local scope.
1013
1014 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001015 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +00001016 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
1017 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 return self.returncode
1019
1020
1021 def wait(self):
1022 """Wait for child process to terminate. Returns returncode
1023 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001024 if self.returncode is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +00001025 _subprocess.WaitForSingleObject(self._handle,
1026 _subprocess.INFINITE)
1027 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001028 return self.returncode
1029
1030
1031 def _readerthread(self, fh, buffer):
1032 buffer.append(fh.read())
Victor Stinner667d4b52010-12-25 22:40:32 +00001033 fh.close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034
1035
Peter Astrand23109f02005-03-03 20:28:59 +00001036 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001037 stdout = None # Return
1038 stderr = None # Return
1039
1040 if self.stdout:
1041 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +00001042 stdout_thread = threading.Thread(target=self._readerthread,
1043 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +00001044 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001045 stdout_thread.start()
1046 if self.stderr:
1047 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +00001048 stderr_thread = threading.Thread(target=self._readerthread,
1049 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +00001050 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051 stderr_thread.start()
1052
1053 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +00001054 if input is not None:
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001055 try:
1056 self.stdin.write(input)
1057 except IOError as e:
1058 if e.errno != errno.EPIPE:
1059 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060 self.stdin.close()
1061
1062 if self.stdout:
1063 stdout_thread.join()
1064 if self.stderr:
1065 stderr_thread.join()
1066
1067 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001068 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001070 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071 stderr = stderr[0]
1072
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 self.wait()
1074 return (stdout, stderr)
1075
Christian Heimesa342c012008-04-20 21:01:16 +00001076 def send_signal(self, sig):
1077 """Send a signal to the process
1078 """
1079 if sig == signal.SIGTERM:
1080 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001081 elif sig == signal.CTRL_C_EVENT:
1082 os.kill(self.pid, signal.CTRL_C_EVENT)
1083 elif sig == signal.CTRL_BREAK_EVENT:
1084 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001085 else:
Brian Curtin19651362010-09-07 13:24:38 +00001086 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001087
1088 def terminate(self):
1089 """Terminates the process
1090 """
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001091 try:
1092 _subprocess.TerminateProcess(self._handle, 1)
1093 except OSError as e:
1094 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1095 # process already died.
1096 if e.winerror != 5:
1097 raise
1098 rc = _subprocess.GetExitCodeProcess(self._handle)
1099 if rc == _subprocess.STILL_ACTIVE:
1100 raise
1101 self.returncode = rc
Christian Heimesa342c012008-04-20 21:01:16 +00001102
1103 kill = terminate
1104
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105 else:
1106 #
1107 # POSIX methods
1108 #
1109 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001110 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1112 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001113 p2cread, p2cwrite = -1, -1
1114 c2pread, c2pwrite = -1, -1
1115 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001116
Peter Astrandd38ddf42005-02-10 08:32:50 +00001117 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001118 pass
1119 elif stdin == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001120 p2cread, p2cwrite = _create_pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001121 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122 p2cread = stdin
1123 else:
1124 # Assuming file-like object
1125 p2cread = stdin.fileno()
1126
Peter Astrandd38ddf42005-02-10 08:32:50 +00001127 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001128 pass
1129 elif stdout == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001130 c2pread, c2pwrite = _create_pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001131 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001132 c2pwrite = stdout
1133 else:
1134 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001135 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001136
Peter Astrandd38ddf42005-02-10 08:32:50 +00001137 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001138 pass
1139 elif stderr == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001140 errread, errwrite = _create_pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001141 elif stderr == STDOUT:
1142 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001143 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001144 errwrite = stderr
1145 else:
1146 # Assuming file-like object
1147 errwrite = stderr.fileno()
1148
1149 return (p2cread, p2cwrite,
1150 c2pread, c2pwrite,
1151 errread, errwrite)
1152
1153
Antoine Pitrou47f14ba2011-01-03 23:42:01 +00001154 def _close_fds(self, fds_to_keep):
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001155 start_fd = 3
Antoine Pitrou47f14ba2011-01-03 23:42:01 +00001156 for fd in sorted(fds_to_keep):
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001157 if fd >= start_fd:
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001158 os.closerange(start_fd, fd)
1159 start_fd = fd + 1
1160 if start_fd <= MAXFD:
1161 os.closerange(start_fd, MAXFD)
1162
1163
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001165 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001166 startupinfo, creationflags, shell,
1167 p2cread, p2cwrite,
1168 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001169 errread, errwrite,
1170 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 """Execute program (POSIX version)"""
1172
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001173 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001175 else:
1176 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001177
1178 if shell:
1179 args = ["/bin/sh", "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001180 if executable:
1181 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001182
Peter Astrandd38ddf42005-02-10 08:32:50 +00001183 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001184 executable = args[0]
Gregory P. Smith5591b022012-10-10 03:34:47 -07001185 orig_executable = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001186
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001187 # For transferring possible exec failure from child to parent.
1188 # Data format: "exception name:hex errno:description"
1189 # Pickle is not used; it is complex and involves memory allocation.
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001190 errpipe_read, errpipe_write = _create_pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001191 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001192 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001194 if _posixsubprocess:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001195 # We must avoid complex work that could involve
1196 # malloc or free in the child process to avoid
1197 # potential deadlocks, thus we do all this here.
1198 # and pass it to fork_exec()
1199
Victor Stinnerf1512a22011-06-21 17:18:38 +02001200 if env is not None:
Victor Stinner449c4662010-05-08 11:10:09 +00001201 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001202 for k, v in env.items()]
1203 else:
1204 env_list = None # Use execv instead of execve.
Victor Stinnerb745a742010-05-18 17:17:23 +00001205 executable = os.fsencode(executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001206 if os.path.dirname(executable):
Victor Stinnerb745a742010-05-18 17:17:23 +00001207 executable_list = (executable,)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001208 else:
1209 # This matches the behavior of os._execvpe().
Victor Stinnerb745a742010-05-18 17:17:23 +00001210 executable_list = tuple(
1211 os.path.join(os.fsencode(dir), executable)
1212 for dir in os.get_exec_path(env))
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001213 fds_to_keep = set(pass_fds)
1214 fds_to_keep.add(errpipe_write)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001215 self.pid = _posixsubprocess.fork_exec(
1216 args, executable_list,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001217 close_fds, sorted(fds_to_keep), cwd, env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001218 p2cread, p2cwrite, c2pread, c2pwrite,
1219 errread, errwrite,
1220 errpipe_read, errpipe_write,
1221 restore_signals, start_new_session, preexec_fn)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001222 self._child_created = True
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001223 else:
1224 # Pure Python implementation: It is not thread safe.
1225 # This implementation may deadlock in the child if your
1226 # parent process has any other threads running.
1227
1228 gc_was_enabled = gc.isenabled()
1229 # Disable gc to avoid bug where gc -> file_dealloc ->
1230 # write to stderr -> hang. See issue1336
1231 gc.disable()
1232 try:
1233 self.pid = os.fork()
1234 except:
1235 if gc_was_enabled:
1236 gc.enable()
1237 raise
1238 self._child_created = True
1239 if self.pid == 0:
1240 # Child
Gregory P. Smith5591b022012-10-10 03:34:47 -07001241 reached_preexec = False
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001242 try:
1243 # Close parent's pipe ends
1244 if p2cwrite != -1:
1245 os.close(p2cwrite)
1246 if c2pread != -1:
1247 os.close(c2pread)
1248 if errread != -1:
1249 os.close(errread)
1250 os.close(errpipe_read)
1251
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001252 # When duping fds, if there arises a situation
1253 # where one of the fds is either 0, 1 or 2, it
1254 # is possible that it is overwritten (#12607).
1255 if c2pwrite == 0:
1256 c2pwrite = os.dup(c2pwrite)
1257 if errwrite == 0 or errwrite == 1:
1258 errwrite = os.dup(errwrite)
1259
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001260 # Dup fds for child
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001261 def _dup2(a, b):
1262 # dup2() removes the CLOEXEC flag but
1263 # we must do it ourselves if dup2()
1264 # would be a no-op (issue #10806).
1265 if a == b:
1266 _set_cloexec(a, False)
1267 elif a != -1:
1268 os.dup2(a, b)
1269 _dup2(p2cread, 0)
1270 _dup2(c2pwrite, 1)
1271 _dup2(errwrite, 2)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001272
1273 # Close pipe fds. Make sure we don't close the
1274 # same fd more than once, or standard fds.
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001275 closed = set()
1276 for fd in [p2cread, c2pwrite, errwrite]:
1277 if fd > 2 and fd not in closed:
1278 os.close(fd)
1279 closed.add(fd)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001280
1281 # Close all other fds, if asked for
1282 if close_fds:
Antoine Pitrou47f14ba2011-01-03 23:42:01 +00001283 fds_to_keep = set(pass_fds)
1284 fds_to_keep.add(errpipe_write)
1285 self._close_fds(fds_to_keep)
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001286
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001287
1288 if cwd is not None:
1289 os.chdir(cwd)
1290
1291 # This is a copy of Python/pythonrun.c
1292 # _Py_RestoreSignals(). If that were exposed
1293 # as a sys._py_restoresignals func it would be
1294 # better.. but this pure python implementation
1295 # isn't likely to be used much anymore.
1296 if restore_signals:
1297 signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
1298 for sig in signals:
1299 if hasattr(signal, sig):
1300 signal.signal(getattr(signal, sig),
1301 signal.SIG_DFL)
1302
1303 if start_new_session and hasattr(os, 'setsid'):
1304 os.setsid()
1305
Gregory P. Smith5591b022012-10-10 03:34:47 -07001306 reached_preexec = True
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001307 if preexec_fn:
1308 preexec_fn()
1309
1310 if env is None:
1311 os.execvp(executable, args)
1312 else:
1313 os.execvpe(executable, args, env)
1314
1315 except:
1316 try:
1317 exc_type, exc_value = sys.exc_info()[:2]
1318 if isinstance(exc_value, OSError):
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001319 errno_num = exc_value.errno
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001320 else:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001321 errno_num = 0
Gregory P. Smith5591b022012-10-10 03:34:47 -07001322 if not reached_preexec:
1323 exc_value = "noexec"
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001324 message = '%s:%x:%s' % (exc_type.__name__,
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001325 errno_num, exc_value)
Victor Stinner4d078042010-04-23 19:28:32 +00001326 message = message.encode(errors="surrogatepass")
1327 os.write(errpipe_write, message)
1328 except Exception:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001329 # We MUST not allow anything odd happening
1330 # above to prevent us from exiting below.
1331 pass
1332
1333 # This exitcode won't be reported to applications
1334 # so it really doesn't matter what we return.
1335 os._exit(255)
1336
1337 # Parent
Facundo Batista10706e22009-06-19 20:34:30 +00001338 if gc_was_enabled:
1339 gc.enable()
Facundo Batista10706e22009-06-19 20:34:30 +00001340 finally:
1341 # be sure the FD is closed no matter what
1342 os.close(errpipe_write)
1343
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001344 if p2cread != -1 and p2cwrite != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001345 os.close(p2cread)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001346 if c2pwrite != -1 and c2pread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001347 os.close(c2pwrite)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001348 if errwrite != -1 and errread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001349 os.close(errwrite)
1350
1351 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001352 # exception (limited in size)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001353 errpipe_data = bytearray()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001354 while True:
1355 part = _eintr_retry_call(os.read, errpipe_read, 50000)
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001356 errpipe_data += part
1357 if not part or len(errpipe_data) > 50000:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001358 break
Facundo Batista10706e22009-06-19 20:34:30 +00001359 finally:
1360 # be sure the FD is closed no matter what
1361 os.close(errpipe_read)
1362
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001363 if errpipe_data:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001364 try:
1365 _eintr_retry_call(os.waitpid, self.pid, 0)
1366 except OSError as e:
1367 if e.errno != errno.ECHILD:
1368 raise
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001369 try:
Gregory P. Smithf44c9da2012-11-10 23:33:17 -08001370 exception_name, hex_errno, err_msg = (
1371 errpipe_data.split(b':', 2))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001372 except ValueError:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001373 exception_name = b'RuntimeError'
1374 hex_errno = b'0'
Gregory P. Smith3aee2222012-11-11 00:04:13 -08001375 err_msg = (b'Bad exception data from child: ' +
1376 repr(errpipe_data))
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001377 child_exception_type = getattr(
1378 builtins, exception_name.decode('ascii'),
1379 RuntimeError)
Victor Stinner4d078042010-04-23 19:28:32 +00001380 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001381 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001382 errno_num = int(hex_errno, 16)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001383 child_exec_never_called = (err_msg == "noexec")
1384 if child_exec_never_called:
1385 err_msg = ""
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001386 if errno_num != 0:
1387 err_msg = os.strerror(errno_num)
1388 if errno_num == errno.ENOENT:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001389 if child_exec_never_called:
1390 # The error must be from chdir(cwd).
1391 err_msg += ': ' + repr(cwd)
1392 else:
1393 err_msg += ': ' + repr(orig_executable)
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001394 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001395 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001396
1397
Brett Cannon84df1e62010-05-14 00:33:40 +00001398 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1399 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1400 _WEXITSTATUS=os.WEXITSTATUS):
1401 # This method is called (indirectly) by __del__, so it cannot
1402 # refer to anything outside of its local scope."""
1403 if _WIFSIGNALED(sts):
1404 self.returncode = -_WTERMSIG(sts)
1405 elif _WIFEXITED(sts):
1406 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001407 else:
1408 # Should never happen
1409 raise RuntimeError("Unknown child exit status!")
1410
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001411
Brett Cannon84df1e62010-05-14 00:33:40 +00001412 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov08bab072012-12-24 20:06:35 +02001413 _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001414 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001415 attribute.
1416
1417 This method is called by __del__, so it cannot reference anything
1418 outside of the local scope (nor can any methods it calls).
1419
1420 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001421 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001422 try:
Brett Cannon84df1e62010-05-14 00:33:40 +00001423 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001424 if pid == self.pid:
1425 self._handle_exitstatus(sts)
Gregory P. Smith39051712012-09-29 11:40:38 -07001426 except _os_error as e:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001427 if _deadstate is not None:
1428 self.returncode = _deadstate
Andrew Svetlov08bab072012-12-24 20:06:35 +02001429 elif e.errno == _ECHILD:
Gregory P. Smith39051712012-09-29 11:40:38 -07001430 # This happens if SIGCLD is set to be ignored or
1431 # waiting for child processes has otherwise been
1432 # disabled for our process. This child is dead, we
1433 # can't get the status.
1434 # http://bugs.python.org/issue15756
1435 self.returncode = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001436 return self.returncode
1437
1438
1439 def wait(self):
1440 """Wait for child process to terminate. Returns returncode
1441 attribute."""
Gregory P. Smith2ec82332012-11-10 20:52:29 -08001442 while self.returncode is None:
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001443 try:
1444 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1445 except OSError as e:
1446 if e.errno != errno.ECHILD:
1447 raise
1448 # This happens if SIGCLD is set to be ignored or waiting
1449 # for child processes has otherwise been disabled for our
1450 # process. This child is dead, we can't get the status.
Gregory P. Smith2ec82332012-11-10 20:52:29 -08001451 pid = self.pid
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001452 sts = 0
Gregory P. Smith2ec82332012-11-10 20:52:29 -08001453 # Check the pid and loop as waitpid has been known to return
1454 # 0 even without WNOHANG in odd situations. issue14396.
1455 if pid == self.pid:
1456 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001457 return self.returncode
1458
1459
Peter Astrand23109f02005-03-03 20:28:59 +00001460 def _communicate(self, input):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001461 if self.stdin:
1462 # Flush stdio buffer. This might block, if the user has
1463 # been writing to .stdin in an uncontrolled fashion.
1464 self.stdin.flush()
1465 if not input:
1466 self.stdin.close()
1467
1468 if _has_poll:
1469 stdout, stderr = self._communicate_with_poll(input)
1470 else:
1471 stdout, stderr = self._communicate_with_select(input)
1472
1473 # All data exchanged. Translate lists into strings.
1474 if stdout is not None:
1475 stdout = b''.join(stdout)
1476 if stderr is not None:
1477 stderr = b''.join(stderr)
1478
1479 # Translate newlines, if requested.
1480 # This also turns bytes into strings.
1481 if self.universal_newlines:
1482 if stdout is not None:
1483 stdout = self._translate_newlines(stdout,
1484 self.stdout.encoding)
1485 if stderr is not None:
1486 stderr = self._translate_newlines(stderr,
1487 self.stderr.encoding)
1488
1489 self.wait()
1490 return (stdout, stderr)
1491
1492
1493 def _communicate_with_poll(self, input):
1494 stdout = None # Return
1495 stderr = None # Return
1496 fd2file = {}
1497 fd2output = {}
1498
1499 poller = select.poll()
1500 def register_and_append(file_obj, eventmask):
1501 poller.register(file_obj.fileno(), eventmask)
1502 fd2file[file_obj.fileno()] = file_obj
1503
1504 def close_unregister_and_remove(fd):
1505 poller.unregister(fd)
1506 fd2file[fd].close()
1507 fd2file.pop(fd)
1508
1509 if self.stdin and input:
1510 register_and_append(self.stdin, select.POLLOUT)
1511
1512 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1513 if self.stdout:
1514 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1515 fd2output[self.stdout.fileno()] = stdout = []
1516 if self.stderr:
1517 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1518 fd2output[self.stderr.fileno()] = stderr = []
1519
1520 input_offset = 0
Serhiy Storchakab3f194d2013-02-04 16:47:39 +02001521 if self.universal_newlines and isinstance(input, str):
1522 input = input.encode(self.stdin.encoding)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001523 while fd2file:
1524 try:
1525 ready = poller.poll()
1526 except select.error as e:
1527 if e.args[0] == errno.EINTR:
1528 continue
1529 raise
1530
1531 # XXX Rewrite these to use non-blocking I/O on the
1532 # file objects; they are no longer using C stdio!
1533
1534 for fd, mode in ready:
1535 if mode & select.POLLOUT:
1536 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001537 try:
1538 input_offset += os.write(fd, chunk)
1539 except OSError as e:
1540 if e.errno == errno.EPIPE:
1541 close_unregister_and_remove(fd)
1542 else:
1543 raise
1544 else:
1545 if input_offset >= len(input):
1546 close_unregister_and_remove(fd)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001547 elif mode & select_POLLIN_POLLPRI:
1548 data = os.read(fd, 4096)
1549 if not data:
1550 close_unregister_and_remove(fd)
1551 fd2output[fd].append(data)
1552 else:
1553 # Ignore hang up or errors.
1554 close_unregister_and_remove(fd)
1555
1556 return (stdout, stderr)
1557
1558
1559 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001560 read_set = []
1561 write_set = []
1562 stdout = None # Return
1563 stderr = None # Return
1564
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001565 if self.stdin and input:
1566 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001567 if self.stdout:
1568 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001569 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001570 if self.stderr:
1571 read_set.append(self.stderr)
1572 stderr = []
1573
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001574 input_offset = 0
Serhiy Storchakab3f194d2013-02-04 16:47:39 +02001575 if self.universal_newlines and isinstance(input, str):
1576 input = input.encode(self.stdin.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001577 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001578 try:
1579 rlist, wlist, xlist = select.select(read_set, write_set, [])
1580 except select.error as e:
1581 if e.args[0] == errno.EINTR:
1582 continue
1583 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001584
Guido van Rossum98297ee2007-11-06 21:34:58 +00001585 # XXX Rewrite these to use non-blocking I/O on the
1586 # file objects; they are no longer using C stdio!
1587
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001588 if self.stdin in wlist:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001589 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001590 try:
1591 bytes_written = os.write(self.stdin.fileno(), chunk)
1592 except OSError as e:
1593 if e.errno == errno.EPIPE:
1594 self.stdin.close()
1595 write_set.remove(self.stdin)
1596 else:
1597 raise
1598 else:
1599 input_offset += bytes_written
1600 if input_offset >= len(input):
1601 self.stdin.close()
1602 write_set.remove(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001603
1604 if self.stdout in rlist:
1605 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001606 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001607 self.stdout.close()
1608 read_set.remove(self.stdout)
1609 stdout.append(data)
1610
1611 if self.stderr in rlist:
1612 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001613 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001614 self.stderr.close()
1615 read_set.remove(self.stderr)
1616 stderr.append(data)
1617
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001618 return (stdout, stderr)
1619
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001620
Christian Heimesa342c012008-04-20 21:01:16 +00001621 def send_signal(self, sig):
1622 """Send a signal to the process
1623 """
1624 os.kill(self.pid, sig)
1625
1626 def terminate(self):
1627 """Terminate the process with SIGTERM
1628 """
1629 self.send_signal(signal.SIGTERM)
1630
1631 def kill(self):
1632 """Kill the process with SIGKILL
1633 """
1634 self.send_signal(signal.SIGKILL)
1635
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001636
1637def _demo_posix():
1638 #
1639 # Example 1: Simple redirection: Get process list
1640 #
1641 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001642 print("Process list:")
1643 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001644
1645 #
1646 # Example 2: Change uid before executing child
1647 #
1648 if os.getuid() == 0:
1649 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1650 p.wait()
1651
1652 #
1653 # Example 3: Connecting several subprocesses
1654 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001655 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001656 p1 = Popen(["dmesg"], stdout=PIPE)
1657 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001658 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001659
1660 #
1661 # Example 4: Catch execution error
1662 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001663 print()
1664 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001665 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001666 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001667 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001668 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001669 print("The file didn't exist. I thought so...")
1670 print("Child traceback:")
1671 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001672 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001673 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001674 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001675 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001676
1677
1678def _demo_windows():
1679 #
1680 # Example 1: Connecting several subprocesses
1681 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001682 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001683 p1 = Popen("set", stdout=PIPE, shell=True)
1684 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001685 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001686
1687 #
1688 # Example 2: Simple execution of program
1689 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001690 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001691 p = Popen("calc")
1692 p.wait()
1693
1694
1695if __name__ == "__main__":
1696 if mswindows:
1697 _demo_windows()
1698 else:
1699 _demo_posix()