blob: 729a53b622ba9fc90cafab776d306d7ce826fbeb [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. Smithf5604852010-12-13 06:45:02 +000030 preexec_fn=None, close_fds=_PLATFORM_DEFAULT, 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,
33 restore_signals=True, start_new_session=False):
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
84varies by platform: False on Windows and True on all other platforms
85such as POSIX.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000086
87if shell is true, the specified command will be executed through the
88shell.
89
90If cwd is not None, the current directory will be changed to cwd
91before the child is executed.
92
Gregory P. Smithf5604852010-12-13 06:45:02 +000093On POSIX, if restore_signals is True all signals that Python sets to
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000094SIG_IGN are restored to SIG_DFL in the child process before the exec.
95Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This
96parameter does nothing on Windows.
97
Gregory P. Smithf5604852010-12-13 06:45:02 +000098On POSIX, if start_new_session is True, the setsid() system call will be made
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000099in the child process prior to executing the command.
100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000101If env is not None, it defines the environment variables for the new
102process.
103
104If universal_newlines is true, the file objects stdout and stderr are
105opened as a text files, but lines may be terminated by any of '\n',
Gregory P. Smithf5604852010-12-13 06:45:02 +0000106the Unix end-of-line convention, '\r', the old Macintosh convention or
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000107'\r\n', the Windows convention. All of these external representations
108are seen as '\n' by the Python program. Note: This feature is only
109available if Python is built with universal newline support (the
110default). Also, the newlines attribute of the file objects stdout,
111stdin and stderr are not updated by the communicate() method.
112
113The startupinfo and creationflags, if given, will be passed to the
114underlying CreateProcess() function. They can specify things such as
115appearance of the main window and priority for the new process.
116(Windows only)
117
118
Georg Brandlf9734072008-12-07 15:30:06 +0000119This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120
Peter Astrand5f5e1412004-12-05 20:15:36 +0000121call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122 Run command with arguments. Wait for command to complete, then
123 return the returncode attribute.
124
125 The arguments are the same as for the Popen constructor. Example:
126
Florent Xicluna4886d242010-03-08 13:27:26 +0000127 >>> retcode = subprocess.call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000128
Peter Astrand454f7672005-01-01 09:36:35 +0000129check_call(*popenargs, **kwargs):
130 Run command with arguments. Wait for command to complete. If the
131 exit code was zero then return, otherwise raise
132 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000134
135 The arguments are the same as for the Popen constructor. Example:
136
Florent Xicluna4886d242010-03-08 13:27:26 +0000137 >>> subprocess.check_call(["ls", "-l"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000138 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139
Brett Cannona23810f2008-05-26 19:04:21 +0000140getstatusoutput(cmd):
141 Return (status, output) of executing cmd in a shell.
142
143 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
144 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
145 returned output will contain output or error messages. A trailing newline
146 is stripped from the output. The exit status for the command can be
147 interpreted according to the rules for the C function wait(). Example:
148
Brett Cannona23810f2008-05-26 19:04:21 +0000149 >>> subprocess.getstatusoutput('ls /bin/ls')
150 (0, '/bin/ls')
151 >>> subprocess.getstatusoutput('cat /bin/junk')
152 (256, 'cat: /bin/junk: No such file or directory')
153 >>> subprocess.getstatusoutput('/bin/junk')
154 (256, 'sh: /bin/junk: not found')
155
156getoutput(cmd):
157 Return output (stdout or stderr) of executing cmd in a shell.
158
159 Like getstatusoutput(), except the exit status is ignored and the return
160 value is a string containing the command's output. Example:
161
Brett Cannona23810f2008-05-26 19:04:21 +0000162 >>> subprocess.getoutput('ls /bin/ls')
163 '/bin/ls'
164
Georg Brandlf9734072008-12-07 15:30:06 +0000165check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000166 Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000167
Georg Brandl2708f3a2009-12-20 14:38:23 +0000168 If the exit code was non-zero it raises a CalledProcessError. The
169 CalledProcessError object will have the return code in the returncode
170 attribute and output in the output attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000171
Georg Brandl2708f3a2009-12-20 14:38:23 +0000172 The arguments are the same as for the Popen constructor. Example:
Georg Brandlf9734072008-12-07 15:30:06 +0000173
Georg Brandl2708f3a2009-12-20 14:38:23 +0000174 >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandlf9734072008-12-07 15:30:06 +0000175
Brett Cannona23810f2008-05-26 19:04:21 +0000176
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177Exceptions
178----------
179Exceptions raised in the child process, before the new program has
180started to execute, will be re-raised in the parent. Additionally,
181the exception object will have one extra attribute called
182'child_traceback', which is a string containing traceback information
183from the childs point of view.
184
185The most common exception raised is OSError. This occurs, for
186example, when trying to execute a non-existent file. Applications
187should prepare for OSErrors.
188
189A ValueError will be raised if Popen is called with invalid arguments.
190
Georg Brandlf9734072008-12-07 15:30:06 +0000191check_call() and check_output() will raise CalledProcessError, if the
192called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000193
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000194
195Security
196--------
197Unlike some other popen functions, this implementation will never call
198/bin/sh implicitly. This means that all characters, including shell
199metacharacters, can safely be passed to child processes.
200
201
202Popen objects
203=============
204Instances of the Popen class have the following methods:
205
206poll()
207 Check if child process has terminated. Returns returncode
208 attribute.
209
210wait()
211 Wait for child process to terminate. Returns returncode attribute.
212
213communicate(input=None)
214 Interact with process: Send data to stdin. Read data from stdout
215 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000216 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 sent to the child process, or None, if no data should be sent to
218 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000219
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 communicate() returns a tuple (stdout, stderr).
221
222 Note: The data read is buffered in memory, so do not use this
223 method if the data size is large or unlimited.
224
225The following attributes are also available:
226
227stdin
228 If the stdin argument is PIPE, this attribute is a file object
229 that provides input to the child process. Otherwise, it is None.
230
231stdout
232 If the stdout argument is PIPE, this attribute is a file object
233 that provides output from the child process. Otherwise, it is
234 None.
235
236stderr
237 If the stderr argument is PIPE, this attribute is file object that
238 provides error output from the child process. Otherwise, it is
239 None.
240
241pid
242 The process ID of the child process.
243
244returncode
245 The child return code. A None value indicates that the process
246 hasn't terminated yet. A negative value -N indicates that the
Gregory P. Smithf5604852010-12-13 06:45:02 +0000247 child was terminated by signal N (POSIX only).
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248
249
250Replacing older functions with the subprocess module
251====================================================
252In this section, "a ==> b" means that b can be used as a replacement
253for a.
254
255Note: All functions in this section fail (more or less) silently if
256the executed program cannot be found; this module raises an OSError
257exception.
258
259In the following examples, we assume that the subprocess module is
260imported with "from subprocess import *".
261
262
263Replacing /bin/sh shell backquote
264---------------------------------
265output=`mycmd myarg`
266==>
267output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
268
269
270Replacing shell pipe line
271-------------------------
272output=`dmesg | grep hda`
273==>
274p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000275p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276output = p2.communicate()[0]
277
278
279Replacing os.system()
280---------------------
281sts = os.system("mycmd" + " myarg")
282==>
283p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000284pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285
286Note:
287
288* Calling the program through the shell is usually not required.
289
290* It's easier to look at the returncode attribute than the
291 exitstatus.
292
293A more real-world example would look like this:
294
295try:
296 retcode = call("mycmd" + " myarg", shell=True)
297 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000298 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000300 print("Child returned", retcode, file=sys.stderr)
301except OSError as e:
302 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303
304
305Replacing os.spawn*
306-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000307P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308
309pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
310==>
311pid = Popen(["/bin/mycmd", "myarg"]).pid
312
313
314P_WAIT example:
315
316retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
317==>
318retcode = call(["/bin/mycmd", "myarg"])
319
320
Tim Peterse718f612004-10-12 21:51:32 +0000321Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322
323os.spawnvp(os.P_NOWAIT, path, args)
324==>
325Popen([path] + args[1:])
326
327
Tim Peterse718f612004-10-12 21:51:32 +0000328Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329
330os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
331==>
332Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000333"""
334
335import sys
336mswindows = (sys.platform == "win32")
337
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000338import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000341import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000342import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000343import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000344import warnings
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345
Peter Astrand454f7672005-01-01 09:36:35 +0000346# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000347class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000348 """This exception is raised when a process run by check_call() or
349 check_output() returns a non-zero exit status.
350 The exit status will be stored in the returncode attribute;
351 check_output() will also store the output in the output attribute.
352 """
353 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000354 self.returncode = returncode
355 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000356 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000357 def __str__(self):
358 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
359
Peter Astrand454f7672005-01-01 09:36:35 +0000360
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361if mswindows:
362 import threading
363 import msvcrt
Brian Curtin1ce6b582010-04-24 16:19:22 +0000364 import _subprocess
365 class STARTUPINFO:
366 dwFlags = 0
367 hStdInput = None
368 hStdOutput = None
369 hStdError = None
370 wShowWindow = 0
371 class pywintypes:
372 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373else:
374 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000375 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 import errno
377 import fcntl
378 import pickle
379
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000380 try:
381 import _posixsubprocess
382 except ImportError:
383 _posixsubprocess = None
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000384 warnings.warn("The _posixsubprocess module is not being used. "
385 "Child process reliability may suffer if your "
386 "program uses threads.", RuntimeWarning)
387
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000388 # When select or poll has indicated that the file is writable,
389 # we can write up to _PIPE_BUF bytes without risk of blocking.
390 # POSIX defines PIPE_BUF as >= 512.
391 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
392
Gregory P. Smith51ee2702010-12-13 07:59:39 +0000393 if _posixsubprocess:
394 _create_pipe = _posixsubprocess.cloexec_pipe
395 else:
396 def _create_pipe():
397 try:
398 cloexec_flag = fcntl.FD_CLOEXEC
399 except AttributeError:
400 cloexec_flag = 1
401
402 fds = os.pipe()
403
404 old = fcntl.fcntl(fds[0], fcntl.F_GETFD)
405 fcntl.fcntl(fds[0], fcntl.F_SETFD, old | cloexec_flag)
406 old = fcntl.fcntl(fds[1], fcntl.F_GETFD)
407 fcntl.fcntl(fds[1], fcntl.F_SETFD, old | cloexec_flag)
408
409 return fds
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000410
Brett Cannona23810f2008-05-26 19:04:21 +0000411__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000412 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413
Brian Curtin1ce6b582010-04-24 16:19:22 +0000414if mswindows:
Brett Cannon84df1e62010-05-14 00:33:40 +0000415 from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
Brian Curtin1ce6b582010-04-24 16:19:22 +0000416 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417try:
418 MAXFD = os.sysconf("SC_OPEN_MAX")
419except:
420 MAXFD = 256
421
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422_active = []
423
424def _cleanup():
425 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000426 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000427 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 try:
429 _active.remove(inst)
430 except ValueError:
431 # This can happen if two threads create a new Popen instance.
432 # It's harmless that it was already removed, so ignore.
433 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434
435PIPE = -1
436STDOUT = -2
437
438
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000439def _eintr_retry_call(func, *args):
440 while True:
441 try:
442 return func(*args)
443 except OSError as e:
444 if e.errno == errno.EINTR:
445 continue
446 raise
447
448
Peter Astrand5f5e1412004-12-05 20:15:36 +0000449def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450 """Run command with arguments. Wait for command to complete, then
451 return the returncode attribute.
452
453 The arguments are the same as for the Popen constructor. Example:
454
455 retcode = call(["ls", "-l"])
456 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000457 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458
459
Peter Astrand454f7672005-01-01 09:36:35 +0000460def check_call(*popenargs, **kwargs):
461 """Run command with arguments. Wait for command to complete. If
462 the exit code was zero then return, otherwise raise
463 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000464 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000465
466 The arguments are the same as for the Popen constructor. Example:
467
468 check_call(["ls", "-l"])
469 """
470 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000471 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000472 cmd = kwargs.get("args")
473 if cmd is None:
474 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000475 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000476 return 0
477
478
479def check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000480 r"""Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000481
482 If the exit code was non-zero it raises a CalledProcessError. The
483 CalledProcessError object will have the return code in the returncode
484 attribute and output in the output attribute.
485
486 The arguments are the same as for the Popen constructor. Example:
487
488 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000489 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000490
491 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000492 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000493
494 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000495 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000496 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000497 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000498 """
499 if 'stdout' in kwargs:
500 raise ValueError('stdout argument not allowed, it will be overridden.')
501 process = Popen(*popenargs, stdout=PIPE, **kwargs)
502 output, unused_err = process.communicate()
503 retcode = process.poll()
504 if retcode:
505 cmd = kwargs.get("args")
506 if cmd is None:
507 cmd = popenargs[0]
508 raise CalledProcessError(retcode, cmd, output=output)
509 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000510
511
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512def list2cmdline(seq):
513 """
514 Translate a sequence of arguments into a command line
515 string, using the same rules as the MS C runtime:
516
517 1) Arguments are delimited by white space, which is either a
518 space or a tab.
519
520 2) A string surrounded by double quotation marks is
521 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000522 contained within. A quoted string can be embedded in an
523 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524
525 3) A double quotation mark preceded by a backslash is
526 interpreted as a literal double quotation mark.
527
528 4) Backslashes are interpreted literally, unless they
529 immediately precede a double quotation mark.
530
531 5) If backslashes immediately precede a double quotation mark,
532 every pair of backslashes is interpreted as a literal
533 backslash. If the number of backslashes is odd, the last
534 backslash escapes the next double quotation mark as
535 described in rule 3.
536 """
537
538 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000539 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
540 # or search http://msdn.microsoft.com for
541 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 result = []
543 needquote = False
544 for arg in seq:
545 bs_buf = []
546
547 # Add a space to separate this argument from the others
548 if result:
549 result.append(' ')
550
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000551 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 if needquote:
553 result.append('"')
554
555 for c in arg:
556 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000557 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 bs_buf.append(c)
559 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000560 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 result.append('\\' * len(bs_buf)*2)
562 bs_buf = []
563 result.append('\\"')
564 else:
565 # Normal char
566 if bs_buf:
567 result.extend(bs_buf)
568 bs_buf = []
569 result.append(c)
570
Christian Heimesfdab48e2008-01-20 09:06:41 +0000571 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572 if bs_buf:
573 result.extend(bs_buf)
574
575 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000576 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577 result.append('"')
578
579 return ''.join(result)
580
581
Brett Cannona23810f2008-05-26 19:04:21 +0000582# Various tools for executing commands and looking at their output and status.
583#
Gregory P. Smithf5604852010-12-13 06:45:02 +0000584# NB This only works (and is only relevant) for POSIX.
Brett Cannona23810f2008-05-26 19:04:21 +0000585
586def getstatusoutput(cmd):
587 """Return (status, output) of executing cmd in a shell.
588
589 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
590 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
591 returned output will contain output or error messages. A trailing newline
592 is stripped from the output. The exit status for the command can be
593 interpreted according to the rules for the C function wait(). Example:
594
595 >>> import subprocess
596 >>> subprocess.getstatusoutput('ls /bin/ls')
597 (0, '/bin/ls')
598 >>> subprocess.getstatusoutput('cat /bin/junk')
599 (256, 'cat: /bin/junk: No such file or directory')
600 >>> subprocess.getstatusoutput('/bin/junk')
601 (256, 'sh: /bin/junk: not found')
602 """
603 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
604 text = pipe.read()
605 sts = pipe.close()
606 if sts is None: sts = 0
607 if text[-1:] == '\n': text = text[:-1]
608 return sts, text
609
610
611def getoutput(cmd):
612 """Return output (stdout or stderr) of executing cmd in a shell.
613
614 Like getstatusoutput(), except the exit status is ignored and the return
615 value is a string containing the command's output. Example:
616
617 >>> import subprocess
618 >>> subprocess.getoutput('ls /bin/ls')
619 '/bin/ls'
620 """
621 return getstatusoutput(cmd)[1]
622
623
Gregory P. Smithf5604852010-12-13 06:45:02 +0000624if mswindows:
625 _PLATFORM_DEFAULT = False
626else:
627 _PLATFORM_DEFAULT = True
628
629
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630class Popen(object):
631 def __init__(self, args, bufsize=0, executable=None,
632 stdin=None, stdout=None, stderr=None,
Gregory P. Smithf5604852010-12-13 06:45:02 +0000633 preexec_fn=None, close_fds=_PLATFORM_DEFAULT, shell=False,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000635 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000636 restore_signals=True, start_new_session=False,
637 pass_fds=()):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 """Create new Popen instance."""
639 _cleanup()
640
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000642 if bufsize is None:
643 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000644 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000645 raise TypeError("bufsize must be an integer")
646
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000648 if preexec_fn is not None:
649 raise ValueError("preexec_fn is not supported on Windows "
650 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000651 if close_fds and (stdin is not None or stdout is not None or
652 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000653 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000654 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 else:
656 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000657 if startupinfo is not None:
658 raise ValueError("startupinfo is only supported on Windows "
659 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000661 raise ValueError("creationflags is only supported on Windows "
662 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000664 if pass_fds and not close_fds:
665 raise ValueError("pass_fds requires close_fds=True.")
666
Tim Peterse718f612004-10-12 21:51:32 +0000667 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 self.stdout = None
669 self.stderr = None
670 self.pid = None
671 self.returncode = None
672 self.universal_newlines = universal_newlines
673
674 # Input and output objects. The general principle is like
675 # this:
676 #
677 # Parent Child
678 # ------ -----
679 # p2cwrite ---stdin---> p2cread
680 # c2pread <--stdout--- c2pwrite
681 # errread <--stderr--- errwrite
682 #
683 # On POSIX, the child objects are file descriptors. On
684 # Windows, these are Windows file handles. The parent objects
685 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000686 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000688
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689 (p2cread, p2cwrite,
690 c2pread, c2pwrite,
691 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
692
693 self._execute_child(args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000694 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000695 startupinfo, creationflags, shell,
696 p2cread, p2cwrite,
697 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000698 errread, errwrite,
699 restore_signals, start_new_session)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700
Thomas Wouterscf297e42007-02-23 15:07:44 +0000701 if mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000702 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000703 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000704 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000705 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000706 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000707 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000708
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000709 if bufsize == 0:
710 bufsize = 1 # Nearly unbuffered (XXX for now)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000711 if p2cwrite != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000712 self.stdin = io.open(p2cwrite, 'wb', bufsize)
713 if self.universal_newlines:
714 self.stdin = io.TextIOWrapper(self.stdin)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000715 if c2pread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000716 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000718 self.stdout = io.TextIOWrapper(self.stdout)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000719 if errread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000720 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000722 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000723
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724
Guido van Rossum98297ee2007-11-06 21:34:58 +0000725 def _translate_newlines(self, data, encoding):
726 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
727 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728
Brian Curtin79cdb662010-12-03 02:46:02 +0000729 def __enter__(self):
730 return self
731
732 def __exit__(self, type, value, traceback):
733 if self.stdout:
734 self.stdout.close()
735 if self.stderr:
736 self.stderr.close()
737 if self.stdin:
738 self.stdin.close()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000739
Brett Cannon84df1e62010-05-14 00:33:40 +0000740 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000741 if not self._child_created:
742 # We didn't get to successfully create a child process.
743 return
744 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000745 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000746 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747 # Child is still running, keep us alive until we can wait on it.
748 _active.append(self)
749
750
Peter Astrand23109f02005-03-03 20:28:59 +0000751 def communicate(self, input=None):
752 """Interact with process: Send data to stdin. Read data from
753 stdout and stderr, until end-of-file is reached. Wait for
754 process to terminate. The optional input argument should be a
755 string to be sent to the child process, or None, if no data
756 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000757
Peter Astrand23109f02005-03-03 20:28:59 +0000758 communicate() returns a tuple (stdout, stderr)."""
759
760 # Optimization: If we are only using one pipe, or no pipe at
761 # all, using select() or threads is unnecessary.
762 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000763 stdout = None
764 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000765 if self.stdin:
766 if input:
767 self.stdin.write(input)
768 self.stdin.close()
769 elif self.stdout:
770 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000771 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000772 elif self.stderr:
773 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000774 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000775 self.wait()
776 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000777
Peter Astrand23109f02005-03-03 20:28:59 +0000778 return self._communicate(input)
779
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000781 def poll(self):
782 return self._internal_poll()
783
784
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 if mswindows:
786 #
787 # Windows methods
788 #
789 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000790 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
792 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000793 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000794 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000795
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000796 p2cread, p2cwrite = -1, -1
797 c2pread, c2pwrite = -1, -1
798 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799
Peter Astrandd38ddf42005-02-10 08:32:50 +0000800 if stdin is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000801 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000802 if p2cread is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000803 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000804 elif stdin == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000805 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000806 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 p2cread = msvcrt.get_osfhandle(stdin)
808 else:
809 # Assuming file-like object
810 p2cread = msvcrt.get_osfhandle(stdin.fileno())
811 p2cread = self._make_inheritable(p2cread)
812
Peter Astrandd38ddf42005-02-10 08:32:50 +0000813 if stdout is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000814 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000815 if c2pwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000816 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000817 elif stdout == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000818 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000819 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820 c2pwrite = msvcrt.get_osfhandle(stdout)
821 else:
822 # Assuming file-like object
823 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
824 c2pwrite = self._make_inheritable(c2pwrite)
825
Peter Astrandd38ddf42005-02-10 08:32:50 +0000826 if stderr is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000827 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000828 if errwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000829 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000830 elif stderr == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000831 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 elif stderr == STDOUT:
833 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000834 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 errwrite = msvcrt.get_osfhandle(stderr)
836 else:
837 # Assuming file-like object
838 errwrite = msvcrt.get_osfhandle(stderr.fileno())
839 errwrite = self._make_inheritable(errwrite)
840
841 return (p2cread, p2cwrite,
842 c2pread, c2pwrite,
843 errread, errwrite)
844
845
846 def _make_inheritable(self, handle):
847 """Return a duplicate of handle, which is inheritable"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000848 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
849 handle, _subprocess.GetCurrentProcess(), 0, 1,
850 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851
852
853 def _find_w9xpopen(self):
854 """Find and return absolut path to w9xpopen.exe"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000855 w9xpopen = os.path.join(
856 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000857 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 if not os.path.exists(w9xpopen):
859 # Eeek - file-not-found - possibly an embedding
860 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000861 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
862 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000863 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000864 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
865 "needed for Popen to work with your "
866 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867 return w9xpopen
868
Tim Peterse718f612004-10-12 21:51:32 +0000869
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000871 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 startupinfo, creationflags, shell,
873 p2cread, p2cwrite,
874 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000875 errread, errwrite,
876 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877 """Execute program (MS Windows version)"""
878
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000879 assert not pass_fds, "pass_fds not yet supported on Windows"
880
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000881 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000882 args = list2cmdline(args)
883
Peter Astrandc1d65362004-11-07 14:30:34 +0000884 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000885 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000886 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +0000887 if -1 not in (p2cread, c2pwrite, errwrite):
Brian Curtin1ce6b582010-04-24 16:19:22 +0000888 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000889 startupinfo.hStdInput = p2cread
890 startupinfo.hStdOutput = c2pwrite
891 startupinfo.hStdError = errwrite
892
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 if shell:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000894 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
895 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000896 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +0000897 args = '{} /c "{}"'.format (comspec, args)
Brian Curtin1ce6b582010-04-24 16:19:22 +0000898 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000899 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 # Win9x, or using command.com on NT. We need to
901 # use the w9xpopen intermediate program. For more
902 # information, see KB Q150956
903 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
904 w9xpopen = self._find_w9xpopen()
905 args = '"%s" %s' % (w9xpopen, args)
906 # Not passing CREATE_NEW_CONSOLE has been known to
907 # cause random failures on win9x. Specifically a
908 # dialog: "Your program accessed mem currently in
909 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000910 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 # kill children.
Brian Curtin1ce6b582010-04-24 16:19:22 +0000912 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000913
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914 # Start the process
915 try:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000916 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000917 # no special security
918 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000919 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000920 creationflags,
921 env,
922 cwd,
923 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000924 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000925 # Translate pywintypes.error to WindowsError, which is
926 # a subclass of OSError. FIXME: We should really
927 # translate errno using _sys_errlist (or simliar), but
928 # how can this be done from Python?
929 raise WindowsError(*e.args)
Tim Goldenad537f22010-08-08 11:18:16 +0000930 finally:
931 # Child is launched. Close the parent's copy of those pipe
932 # handles that only the child should have open. You need
933 # to make sure that no handles to the write end of the
934 # output pipe are maintained in this process or else the
935 # pipe will not close when the child process exits and the
936 # ReadFile will hang.
937 if p2cread != -1:
938 p2cread.Close()
939 if c2pwrite != -1:
940 c2pwrite.Close()
941 if errwrite != -1:
942 errwrite.Close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943
944 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000945 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 self._handle = hp
947 self.pid = pid
948 ht.Close()
949
Brett Cannon84df1e62010-05-14 00:33:40 +0000950 def _internal_poll(self, _deadstate=None,
Victor Stinnerc807a612010-05-14 21:53:45 +0000951 _WaitForSingleObject=_subprocess.WaitForSingleObject,
952 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
953 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000954 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +0000955 attribute.
956
957 This method is called by __del__, so it can only refer to objects
958 in its local scope.
959
960 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000961 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +0000962 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
963 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 return self.returncode
965
966
967 def wait(self):
968 """Wait for child process to terminate. Returns returncode
969 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000970 if self.returncode is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000971 _subprocess.WaitForSingleObject(self._handle,
972 _subprocess.INFINITE)
973 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 return self.returncode
975
976
977 def _readerthread(self, fh, buffer):
978 buffer.append(fh.read())
979
980
Peter Astrand23109f02005-03-03 20:28:59 +0000981 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 stdout = None # Return
983 stderr = None # Return
984
985 if self.stdout:
986 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000987 stdout_thread = threading.Thread(target=self._readerthread,
988 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000989 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 stdout_thread.start()
991 if self.stderr:
992 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000993 stderr_thread = threading.Thread(target=self._readerthread,
994 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000995 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 stderr_thread.start()
997
998 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000999 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 self.stdin.write(input)
1001 self.stdin.close()
1002
1003 if self.stdout:
1004 stdout_thread.join()
1005 if self.stderr:
1006 stderr_thread.join()
1007
1008 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001009 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001011 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012 stderr = stderr[0]
1013
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014 self.wait()
1015 return (stdout, stderr)
1016
Christian Heimesa342c012008-04-20 21:01:16 +00001017 def send_signal(self, sig):
1018 """Send a signal to the process
1019 """
1020 if sig == signal.SIGTERM:
1021 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001022 elif sig == signal.CTRL_C_EVENT:
1023 os.kill(self.pid, signal.CTRL_C_EVENT)
1024 elif sig == signal.CTRL_BREAK_EVENT:
1025 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001026 else:
Brian Curtin19651362010-09-07 13:24:38 +00001027 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001028
1029 def terminate(self):
1030 """Terminates the process
1031 """
Brian Curtin1ce6b582010-04-24 16:19:22 +00001032 _subprocess.TerminateProcess(self._handle, 1)
Christian Heimesa342c012008-04-20 21:01:16 +00001033
1034 kill = terminate
1035
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 else:
1037 #
1038 # POSIX methods
1039 #
1040 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001041 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001042 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1043 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001044 p2cread, p2cwrite = -1, -1
1045 c2pread, c2pwrite = -1, -1
1046 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047
Peter Astrandd38ddf42005-02-10 08:32:50 +00001048 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049 pass
1050 elif stdin == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001051 p2cread, p2cwrite = _create_pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001052 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053 p2cread = stdin
1054 else:
1055 # Assuming file-like object
1056 p2cread = stdin.fileno()
1057
Peter Astrandd38ddf42005-02-10 08:32:50 +00001058 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059 pass
1060 elif stdout == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001061 c2pread, c2pwrite = _create_pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001062 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063 c2pwrite = stdout
1064 else:
1065 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001066 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067
Peter Astrandd38ddf42005-02-10 08:32:50 +00001068 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 pass
1070 elif stderr == PIPE:
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001071 errread, errwrite = _create_pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 elif stderr == STDOUT:
1073 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001074 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075 errwrite = stderr
1076 else:
1077 # Assuming file-like object
1078 errwrite = stderr.fileno()
1079
1080 return (p2cread, p2cwrite,
1081 c2pread, c2pwrite,
1082 errread, errwrite)
1083
1084
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001086 os.closerange(3, but)
1087 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001088
1089
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001090 def _close_all_but_a_sorted_few_fds(self, fds_to_keep):
1091 # precondition: fds_to_keep must be sorted and unique
1092 start_fd = 3
1093 for fd in fds_to_keep:
1094 if fd > start_fd:
1095 os.closerange(start_fd, fd)
1096 start_fd = fd + 1
1097 if start_fd <= MAXFD:
1098 os.closerange(start_fd, MAXFD)
1099
1100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001101 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001102 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001103 startupinfo, creationflags, shell,
1104 p2cread, p2cwrite,
1105 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001106 errread, errwrite,
1107 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108 """Execute program (POSIX version)"""
1109
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001110 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001112 else:
1113 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114
1115 if shell:
1116 args = ["/bin/sh", "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001117 if executable:
1118 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001119
Peter Astrandd38ddf42005-02-10 08:32:50 +00001120 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001121 executable = args[0]
1122
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001123 # For transferring possible exec failure from child to parent.
1124 # Data format: "exception name:hex errno:description"
1125 # Pickle is not used; it is complex and involves memory allocation.
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001126 errpipe_read, errpipe_write = _create_pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001127 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001128 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001129
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001130 if _posixsubprocess:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001131 # We must avoid complex work that could involve
1132 # malloc or free in the child process to avoid
1133 # potential deadlocks, thus we do all this here.
1134 # and pass it to fork_exec()
1135
1136 if env:
Victor Stinner449c4662010-05-08 11:10:09 +00001137 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001138 for k, v in env.items()]
1139 else:
1140 env_list = None # Use execv instead of execve.
Victor Stinnerb745a742010-05-18 17:17:23 +00001141 executable = os.fsencode(executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001142 if os.path.dirname(executable):
Victor Stinnerb745a742010-05-18 17:17:23 +00001143 executable_list = (executable,)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001144 else:
1145 # This matches the behavior of os._execvpe().
Victor Stinnerb745a742010-05-18 17:17:23 +00001146 executable_list = tuple(
1147 os.path.join(os.fsencode(dir), executable)
1148 for dir in os.get_exec_path(env))
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001149 fds_to_keep = set(pass_fds)
1150 fds_to_keep.add(errpipe_write)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001151 self.pid = _posixsubprocess.fork_exec(
1152 args, executable_list,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001153 close_fds, sorted(fds_to_keep), cwd, env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001154 p2cread, p2cwrite, c2pread, c2pwrite,
1155 errread, errwrite,
1156 errpipe_read, errpipe_write,
1157 restore_signals, start_new_session, preexec_fn)
1158 else:
1159 # Pure Python implementation: It is not thread safe.
1160 # This implementation may deadlock in the child if your
1161 # parent process has any other threads running.
1162
1163 gc_was_enabled = gc.isenabled()
1164 # Disable gc to avoid bug where gc -> file_dealloc ->
1165 # write to stderr -> hang. See issue1336
1166 gc.disable()
1167 try:
1168 self.pid = os.fork()
1169 except:
1170 if gc_was_enabled:
1171 gc.enable()
1172 raise
1173 self._child_created = True
1174 if self.pid == 0:
1175 # Child
1176 try:
1177 # Close parent's pipe ends
1178 if p2cwrite != -1:
1179 os.close(p2cwrite)
1180 if c2pread != -1:
1181 os.close(c2pread)
1182 if errread != -1:
1183 os.close(errread)
1184 os.close(errpipe_read)
1185
1186 # Dup fds for child
1187 if p2cread != -1:
1188 os.dup2(p2cread, 0)
1189 if c2pwrite != -1:
1190 os.dup2(c2pwrite, 1)
1191 if errwrite != -1:
1192 os.dup2(errwrite, 2)
1193
1194 # Close pipe fds. Make sure we don't close the
1195 # same fd more than once, or standard fds.
1196 if p2cread != -1 and p2cread not in (0,):
1197 os.close(p2cread)
1198 if (c2pwrite != -1 and
1199 c2pwrite not in (p2cread, 1)):
1200 os.close(c2pwrite)
1201 if (errwrite != -1 and
1202 errwrite not in (p2cread, c2pwrite, 2)):
1203 os.close(errwrite)
1204
1205 # Close all other fds, if asked for
1206 if close_fds:
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001207 if pass_fds:
1208 fds_to_keep = set(pass_fds)
1209 fds_to_keep.add(errpipe_write)
1210 self._close_all_but_a_sorted_few_fds(
1211 sorted(fds_to_keep))
1212 else:
1213 self._close_fds(but=errpipe_write)
1214
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001215
1216 if cwd is not None:
1217 os.chdir(cwd)
1218
1219 # This is a copy of Python/pythonrun.c
1220 # _Py_RestoreSignals(). If that were exposed
1221 # as a sys._py_restoresignals func it would be
1222 # better.. but this pure python implementation
1223 # isn't likely to be used much anymore.
1224 if restore_signals:
1225 signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
1226 for sig in signals:
1227 if hasattr(signal, sig):
1228 signal.signal(getattr(signal, sig),
1229 signal.SIG_DFL)
1230
1231 if start_new_session and hasattr(os, 'setsid'):
1232 os.setsid()
1233
1234 if preexec_fn:
1235 preexec_fn()
1236
1237 if env is None:
1238 os.execvp(executable, args)
1239 else:
1240 os.execvpe(executable, args, env)
1241
1242 except:
1243 try:
1244 exc_type, exc_value = sys.exc_info()[:2]
1245 if isinstance(exc_value, OSError):
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001246 errno_num = exc_value.errno
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001247 else:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001248 errno_num = 0
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001249 message = '%s:%x:%s' % (exc_type.__name__,
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001250 errno_num, exc_value)
Victor Stinner4d078042010-04-23 19:28:32 +00001251 message = message.encode(errors="surrogatepass")
1252 os.write(errpipe_write, message)
1253 except Exception:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001254 # We MUST not allow anything odd happening
1255 # above to prevent us from exiting below.
1256 pass
1257
1258 # This exitcode won't be reported to applications
1259 # so it really doesn't matter what we return.
1260 os._exit(255)
1261
1262 # Parent
Facundo Batista10706e22009-06-19 20:34:30 +00001263 if gc_was_enabled:
1264 gc.enable()
Facundo Batista10706e22009-06-19 20:34:30 +00001265 finally:
1266 # be sure the FD is closed no matter what
1267 os.close(errpipe_write)
1268
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001269 if p2cread != -1 and p2cwrite != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001270 os.close(p2cread)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001271 if c2pwrite != -1 and c2pread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001272 os.close(c2pwrite)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001273 if errwrite != -1 and errread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001274 os.close(errwrite)
1275
1276 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001277 # exception (limited in size)
1278 data = bytearray()
1279 while True:
1280 part = _eintr_retry_call(os.read, errpipe_read, 50000)
1281 data += part
1282 if not part or len(data) > 50000:
1283 break
Facundo Batista10706e22009-06-19 20:34:30 +00001284 finally:
1285 # be sure the FD is closed no matter what
1286 os.close(errpipe_read)
1287
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001288 if data:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001289 _eintr_retry_call(os.waitpid, self.pid, 0)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001290 try:
1291 exception_name, hex_errno, err_msg = data.split(b':', 2)
1292 except ValueError:
1293 print('Bad exception data:', repr(data))
1294 exception_name = b'RuntimeError'
1295 hex_errno = b'0'
1296 err_msg = b'Unknown'
1297 child_exception_type = getattr(
1298 builtins, exception_name.decode('ascii'),
1299 RuntimeError)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001300 for fd in (p2cwrite, c2pread, errread):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001301 if fd != -1:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001302 os.close(fd)
Victor Stinner4d078042010-04-23 19:28:32 +00001303 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001304 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001305 errno_num = int(hex_errno, 16)
1306 if errno_num != 0:
1307 err_msg = os.strerror(errno_num)
1308 if errno_num == errno.ENOENT:
Benjamin Peterson5f780402010-11-20 18:07:52 +00001309 err_msg += ': ' + repr(args[0])
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001310 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001311 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001312
1313
Brett Cannon84df1e62010-05-14 00:33:40 +00001314 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1315 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1316 _WEXITSTATUS=os.WEXITSTATUS):
1317 # This method is called (indirectly) by __del__, so it cannot
1318 # refer to anything outside of its local scope."""
1319 if _WIFSIGNALED(sts):
1320 self.returncode = -_WTERMSIG(sts)
1321 elif _WIFEXITED(sts):
1322 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001323 else:
1324 # Should never happen
1325 raise RuntimeError("Unknown child exit status!")
1326
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001327
Brett Cannon84df1e62010-05-14 00:33:40 +00001328 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
1329 _WNOHANG=os.WNOHANG, _os_error=os.error):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001330 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001331 attribute.
1332
1333 This method is called by __del__, so it cannot reference anything
1334 outside of the local scope (nor can any methods it calls).
1335
1336 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001337 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001338 try:
Brett Cannon84df1e62010-05-14 00:33:40 +00001339 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001340 if pid == self.pid:
1341 self._handle_exitstatus(sts)
Brett Cannon84df1e62010-05-14 00:33:40 +00001342 except _os_error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001343 if _deadstate is not None:
1344 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001345 return self.returncode
1346
1347
1348 def wait(self):
1349 """Wait for child process to terminate. Returns returncode
1350 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001351 if self.returncode is None:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001352 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001353 self._handle_exitstatus(sts)
1354 return self.returncode
1355
1356
Peter Astrand23109f02005-03-03 20:28:59 +00001357 def _communicate(self, input):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001358 if self.stdin:
1359 # Flush stdio buffer. This might block, if the user has
1360 # been writing to .stdin in an uncontrolled fashion.
1361 self.stdin.flush()
1362 if not input:
1363 self.stdin.close()
1364
1365 if _has_poll:
1366 stdout, stderr = self._communicate_with_poll(input)
1367 else:
1368 stdout, stderr = self._communicate_with_select(input)
1369
1370 # All data exchanged. Translate lists into strings.
1371 if stdout is not None:
1372 stdout = b''.join(stdout)
1373 if stderr is not None:
1374 stderr = b''.join(stderr)
1375
1376 # Translate newlines, if requested.
1377 # This also turns bytes into strings.
1378 if self.universal_newlines:
1379 if stdout is not None:
1380 stdout = self._translate_newlines(stdout,
1381 self.stdout.encoding)
1382 if stderr is not None:
1383 stderr = self._translate_newlines(stderr,
1384 self.stderr.encoding)
1385
1386 self.wait()
1387 return (stdout, stderr)
1388
1389
1390 def _communicate_with_poll(self, input):
1391 stdout = None # Return
1392 stderr = None # Return
1393 fd2file = {}
1394 fd2output = {}
1395
1396 poller = select.poll()
1397 def register_and_append(file_obj, eventmask):
1398 poller.register(file_obj.fileno(), eventmask)
1399 fd2file[file_obj.fileno()] = file_obj
1400
1401 def close_unregister_and_remove(fd):
1402 poller.unregister(fd)
1403 fd2file[fd].close()
1404 fd2file.pop(fd)
1405
1406 if self.stdin and input:
1407 register_and_append(self.stdin, select.POLLOUT)
1408
1409 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1410 if self.stdout:
1411 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1412 fd2output[self.stdout.fileno()] = stdout = []
1413 if self.stderr:
1414 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1415 fd2output[self.stderr.fileno()] = stderr = []
1416
1417 input_offset = 0
1418 while fd2file:
1419 try:
1420 ready = poller.poll()
1421 except select.error as e:
1422 if e.args[0] == errno.EINTR:
1423 continue
1424 raise
1425
1426 # XXX Rewrite these to use non-blocking I/O on the
1427 # file objects; they are no longer using C stdio!
1428
1429 for fd, mode in ready:
1430 if mode & select.POLLOUT:
1431 chunk = input[input_offset : input_offset + _PIPE_BUF]
1432 input_offset += os.write(fd, chunk)
1433 if input_offset >= len(input):
1434 close_unregister_and_remove(fd)
1435 elif mode & select_POLLIN_POLLPRI:
1436 data = os.read(fd, 4096)
1437 if not data:
1438 close_unregister_and_remove(fd)
1439 fd2output[fd].append(data)
1440 else:
1441 # Ignore hang up or errors.
1442 close_unregister_and_remove(fd)
1443
1444 return (stdout, stderr)
1445
1446
1447 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001448 read_set = []
1449 write_set = []
1450 stdout = None # Return
1451 stderr = None # Return
1452
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001453 if self.stdin and input:
1454 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001455 if self.stdout:
1456 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001457 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458 if self.stderr:
1459 read_set.append(self.stderr)
1460 stderr = []
1461
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001462 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001463 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001464 try:
1465 rlist, wlist, xlist = select.select(read_set, write_set, [])
1466 except select.error as e:
1467 if e.args[0] == errno.EINTR:
1468 continue
1469 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001470
Guido van Rossum98297ee2007-11-06 21:34:58 +00001471 # XXX Rewrite these to use non-blocking I/O on the
1472 # file objects; they are no longer using C stdio!
1473
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001474 if self.stdin in wlist:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001475 chunk = input[input_offset : input_offset + _PIPE_BUF]
Guido van Rossumbae07c92007-10-08 02:46:15 +00001476 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001477 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001478 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001479 self.stdin.close()
1480 write_set.remove(self.stdin)
1481
1482 if self.stdout in rlist:
1483 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001484 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001485 self.stdout.close()
1486 read_set.remove(self.stdout)
1487 stdout.append(data)
1488
1489 if self.stderr in rlist:
1490 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001491 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001492 self.stderr.close()
1493 read_set.remove(self.stderr)
1494 stderr.append(data)
1495
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001496 return (stdout, stderr)
1497
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001498
Christian Heimesa342c012008-04-20 21:01:16 +00001499 def send_signal(self, sig):
1500 """Send a signal to the process
1501 """
1502 os.kill(self.pid, sig)
1503
1504 def terminate(self):
1505 """Terminate the process with SIGTERM
1506 """
1507 self.send_signal(signal.SIGTERM)
1508
1509 def kill(self):
1510 """Kill the process with SIGKILL
1511 """
1512 self.send_signal(signal.SIGKILL)
1513
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001514
1515def _demo_posix():
1516 #
1517 # Example 1: Simple redirection: Get process list
1518 #
1519 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001520 print("Process list:")
1521 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001522
1523 #
1524 # Example 2: Change uid before executing child
1525 #
1526 if os.getuid() == 0:
1527 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1528 p.wait()
1529
1530 #
1531 # Example 3: Connecting several subprocesses
1532 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001533 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001534 p1 = Popen(["dmesg"], stdout=PIPE)
1535 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001536 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001537
1538 #
1539 # Example 4: Catch execution error
1540 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001541 print()
1542 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001543 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001544 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001545 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001546 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001547 print("The file didn't exist. I thought so...")
1548 print("Child traceback:")
1549 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001550 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001551 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001552 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001553 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001554
1555
1556def _demo_windows():
1557 #
1558 # Example 1: Connecting several subprocesses
1559 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001560 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001561 p1 = Popen("set", stdout=PIPE, shell=True)
1562 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001563 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001564
1565 #
1566 # Example 2: Simple execution of program
1567 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001568 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001569 p = Popen("calc")
1570 p.wait()
1571
1572
1573if __name__ == "__main__":
1574 if mswindows:
1575 _demo_windows()
1576 else:
1577 _demo_posix()