blob: 2e7864c77fd370f67936be8d333fd5fb02958c6e [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,
30 preexec_fn=None, close_fds=False, shell=False,
31 cwd=None, env=None, universal_newlines=False,
32 startupinfo=None, creationflags=0):
33
34
35Arguments are:
36
37args should be a string, or a sequence of program arguments. The
38program to execute is normally the first item in the args sequence or
39string, but can be explicitly set by using the executable argument.
40
41On UNIX, with shell=False (default): In this case, the Popen class
42uses os.execvp() to execute the child program. args should normally
43be a sequence. A string will be treated as a sequence with the string
44as the only item (the program to execute).
45
46On UNIX, with shell=True: If args is a string, it specifies the
47command string to execute through the shell. If args is a sequence,
48the first item specifies the command string, and any additional items
49will be treated as additional shell arguments.
50
51On Windows: the Popen class uses CreateProcess() to execute the child
52program, which operates on strings. If args is a sequence, it will be
53converted to a string using the list2cmdline method. Please note that
54not all MS Windows applications interpret the command line the same
55way: The list2cmdline is designed for applications using the same
56rules as the MS C runtime.
57
58bufsize, if given, has the same meaning as the corresponding argument
59to the built-in open() function: 0 means unbuffered, 1 means line
60buffered, any other positive value means use a buffer of
61(approximately) that size. A negative bufsize means to use the system
62default, which usually means fully buffered. The default value for
63bufsize is 0 (unbuffered).
64
65stdin, stdout and stderr specify the executed programs' standard
66input, standard output and standard error file handles, respectively.
67Valid values are PIPE, an existing file descriptor (a positive
68integer), an existing file object, and None. PIPE indicates that a
69new pipe to the child should be created. With None, no redirection
70will occur; the child's file handles will be inherited from the
71parent. Additionally, stderr can be STDOUT, which indicates that the
72stderr data from the applications should be captured into the same
73file handle as for stdout.
74
75If preexec_fn is set to a callable object, this object will be called
76in the child process just before the child is executed.
77
78If close_fds is true, all file descriptors except 0, 1 and 2 will be
79closed before the child process is executed.
80
81if shell is true, the specified command will be executed through the
82shell.
83
84If cwd is not None, the current directory will be changed to cwd
85before the child is executed.
86
87If env is not None, it defines the environment variables for the new
88process.
89
90If universal_newlines is true, the file objects stdout and stderr are
91opened as a text files, but lines may be terminated by any of '\n',
92the Unix end-of-line convention, '\r', the Macintosh convention or
93'\r\n', the Windows convention. All of these external representations
94are seen as '\n' by the Python program. Note: This feature is only
95available if Python is built with universal newline support (the
96default). Also, the newlines attribute of the file objects stdout,
97stdin and stderr are not updated by the communicate() method.
98
99The startupinfo and creationflags, if given, will be passed to the
100underlying CreateProcess() function. They can specify things such as
101appearance of the main window and priority for the new process.
102(Windows only)
103
104
Georg Brandlf9734072008-12-07 15:30:06 +0000105This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000106
Peter Astrand5f5e1412004-12-05 20:15:36 +0000107call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 Run command with arguments. Wait for command to complete, then
109 return the returncode attribute.
110
111 The arguments are the same as for the Popen constructor. Example:
112
113 retcode = call(["ls", "-l"])
114
Peter Astrand454f7672005-01-01 09:36:35 +0000115check_call(*popenargs, **kwargs):
116 Run command with arguments. Wait for command to complete. If the
117 exit code was zero then return, otherwise raise
118 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000120
121 The arguments are the same as for the Popen constructor. Example:
122
123 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000124
Brett Cannona23810f2008-05-26 19:04:21 +0000125getstatusoutput(cmd):
126 Return (status, output) of executing cmd in a shell.
127
128 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
129 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
130 returned output will contain output or error messages. A trailing newline
131 is stripped from the output. The exit status for the command can be
132 interpreted according to the rules for the C function wait(). Example:
133
134 >>> import subprocess
135 >>> subprocess.getstatusoutput('ls /bin/ls')
136 (0, '/bin/ls')
137 >>> subprocess.getstatusoutput('cat /bin/junk')
138 (256, 'cat: /bin/junk: No such file or directory')
139 >>> subprocess.getstatusoutput('/bin/junk')
140 (256, 'sh: /bin/junk: not found')
141
142getoutput(cmd):
143 Return output (stdout or stderr) of executing cmd in a shell.
144
145 Like getstatusoutput(), except the exit status is ignored and the return
146 value is a string containing the command's output. Example:
147
148 >>> import subprocess
149 >>> subprocess.getoutput('ls /bin/ls')
150 '/bin/ls'
151
Georg Brandlf9734072008-12-07 15:30:06 +0000152check_output(*popenargs, **kwargs):
153 Run command with arguments and return its output as a byte string.
154
155 If the exit code was non-zero it raises a CalledProcessError. The
156 CalledProcessError object will have the return code in the returncode
157 attribute and output in the output attribute.
158
159 The arguments are the same as for the Popen constructor. Example:
160
161 output = subprocess.check_output(["ls", "-l", "/dev/null"])
162
Brett Cannona23810f2008-05-26 19:04:21 +0000163
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000164Exceptions
165----------
166Exceptions raised in the child process, before the new program has
167started to execute, will be re-raised in the parent. Additionally,
168the exception object will have one extra attribute called
169'child_traceback', which is a string containing traceback information
170from the childs point of view.
171
172The most common exception raised is OSError. This occurs, for
173example, when trying to execute a non-existent file. Applications
174should prepare for OSErrors.
175
176A ValueError will be raised if Popen is called with invalid arguments.
177
Georg Brandlf9734072008-12-07 15:30:06 +0000178check_call() and check_output() will raise CalledProcessError, if the
179called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000180
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181
182Security
183--------
184Unlike some other popen functions, this implementation will never call
185/bin/sh implicitly. This means that all characters, including shell
186metacharacters, can safely be passed to child processes.
187
188
189Popen objects
190=============
191Instances of the Popen class have the following methods:
192
193poll()
194 Check if child process has terminated. Returns returncode
195 attribute.
196
197wait()
198 Wait for child process to terminate. Returns returncode attribute.
199
200communicate(input=None)
201 Interact with process: Send data to stdin. Read data from stdout
202 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000203 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 sent to the child process, or None, if no data should be sent to
205 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000206
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207 communicate() returns a tuple (stdout, stderr).
208
209 Note: The data read is buffered in memory, so do not use this
210 method if the data size is large or unlimited.
211
212The following attributes are also available:
213
214stdin
215 If the stdin argument is PIPE, this attribute is a file object
216 that provides input to the child process. Otherwise, it is None.
217
218stdout
219 If the stdout argument is PIPE, this attribute is a file object
220 that provides output from the child process. Otherwise, it is
221 None.
222
223stderr
224 If the stderr argument is PIPE, this attribute is file object that
225 provides error output from the child process. Otherwise, it is
226 None.
227
228pid
229 The process ID of the child process.
230
231returncode
232 The child return code. A None value indicates that the process
233 hasn't terminated yet. A negative value -N indicates that the
234 child was terminated by signal N (UNIX only).
235
236
237Replacing older functions with the subprocess module
238====================================================
239In this section, "a ==> b" means that b can be used as a replacement
240for a.
241
242Note: All functions in this section fail (more or less) silently if
243the executed program cannot be found; this module raises an OSError
244exception.
245
246In the following examples, we assume that the subprocess module is
247imported with "from subprocess import *".
248
249
250Replacing /bin/sh shell backquote
251---------------------------------
252output=`mycmd myarg`
253==>
254output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
255
256
257Replacing shell pipe line
258-------------------------
259output=`dmesg | grep hda`
260==>
261p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000262p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263output = p2.communicate()[0]
264
265
266Replacing os.system()
267---------------------
268sts = os.system("mycmd" + " myarg")
269==>
270p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000271pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000272
273Note:
274
275* Calling the program through the shell is usually not required.
276
277* It's easier to look at the returncode attribute than the
278 exitstatus.
279
280A more real-world example would look like this:
281
282try:
283 retcode = call("mycmd" + " myarg", shell=True)
284 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000285 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000287 print("Child returned", retcode, file=sys.stderr)
288except OSError as e:
289 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290
291
292Replacing os.spawn*
293-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000294P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295
296pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
297==>
298pid = Popen(["/bin/mycmd", "myarg"]).pid
299
300
301P_WAIT example:
302
303retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
304==>
305retcode = call(["/bin/mycmd", "myarg"])
306
307
Tim Peterse718f612004-10-12 21:51:32 +0000308Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309
310os.spawnvp(os.P_NOWAIT, path, args)
311==>
312Popen([path] + args[1:])
313
314
Tim Peterse718f612004-10-12 21:51:32 +0000315Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316
317os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
318==>
319Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320"""
321
322import sys
323mswindows = (sys.platform == "win32")
324
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000325import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000328import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000329import signal
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330
Peter Astrand454f7672005-01-01 09:36:35 +0000331# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000332class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000333 """This exception is raised when a process run by check_call() or
334 check_output() returns a non-zero exit status.
335 The exit status will be stored in the returncode attribute;
336 check_output() will also store the output in the output attribute.
337 """
338 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339 self.returncode = returncode
340 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000341 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000342 def __str__(self):
343 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
344
Peter Astrand454f7672005-01-01 09:36:35 +0000345
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000346if mswindows:
347 import threading
348 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000349 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000351 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
352 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
353 from win32api import GetCurrentProcess, DuplicateHandle, \
354 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000355 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000357 from win32process import CreateProcess, STARTUPINFO, \
358 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000359 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Christian Heimesa342c012008-04-20 21:01:16 +0000360 from win32process import TerminateProcess
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000362 else:
363 from _subprocess import *
364 class STARTUPINFO:
365 dwFlags = 0
366 hStdInput = None
367 hStdOutput = None
368 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000369 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000370 class pywintypes:
371 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372else:
373 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000374 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375 import errno
376 import fcntl
377 import pickle
378
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000379 # When select or poll has indicated that the file is writable,
380 # we can write up to _PIPE_BUF bytes without risk of blocking.
381 # POSIX defines PIPE_BUF as >= 512.
382 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
383
384
Brett Cannona23810f2008-05-26 19:04:21 +0000385__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000386 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387
388try:
389 MAXFD = os.sysconf("SC_OPEN_MAX")
390except:
391 MAXFD = 256
392
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393_active = []
394
395def _cleanup():
396 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000397 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000398 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 try:
400 _active.remove(inst)
401 except ValueError:
402 # This can happen if two threads create a new Popen instance.
403 # It's harmless that it was already removed, so ignore.
404 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405
406PIPE = -1
407STDOUT = -2
408
409
Peter Astrand5f5e1412004-12-05 20:15:36 +0000410def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 """Run command with arguments. Wait for command to complete, then
412 return the returncode attribute.
413
414 The arguments are the same as for the Popen constructor. Example:
415
416 retcode = call(["ls", "-l"])
417 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000418 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419
420
Peter Astrand454f7672005-01-01 09:36:35 +0000421def check_call(*popenargs, **kwargs):
422 """Run command with arguments. Wait for command to complete. If
423 the exit code was zero then return, otherwise raise
424 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000425 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000426
427 The arguments are the same as for the Popen constructor. Example:
428
429 check_call(["ls", "-l"])
430 """
431 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000432 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000433 cmd = kwargs.get("args")
434 if cmd is None:
435 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000436 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000437 return 0
438
439
440def check_output(*popenargs, **kwargs):
441 """Run command with arguments and return its output as a byte string.
442
443 If the exit code was non-zero it raises a CalledProcessError. The
444 CalledProcessError object will have the return code in the returncode
445 attribute and output in the output attribute.
446
447 The arguments are the same as for the Popen constructor. Example:
448
449 >>> check_output(["ls", "-l", "/dev/null"])
450 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
451
452 The stdout argument is not allowed as it is used internally.
453 To capture standard error in the result, use stderr=subprocess.STDOUT.
454
455 >>> check_output(["/bin/sh", "-c",
Mark Dickinson934896d2009-02-21 20:59:32 +0000456 "ls -l non_existent_file ; exit 0"],
Georg Brandlf9734072008-12-07 15:30:06 +0000457 stderr=subprocess.STDOUT)
Mark Dickinson934896d2009-02-21 20:59:32 +0000458 'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000459 """
460 if 'stdout' in kwargs:
461 raise ValueError('stdout argument not allowed, it will be overridden.')
462 process = Popen(*popenargs, stdout=PIPE, **kwargs)
463 output, unused_err = process.communicate()
464 retcode = process.poll()
465 if retcode:
466 cmd = kwargs.get("args")
467 if cmd is None:
468 cmd = popenargs[0]
469 raise CalledProcessError(retcode, cmd, output=output)
470 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000471
472
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473def list2cmdline(seq):
474 """
475 Translate a sequence of arguments into a command line
476 string, using the same rules as the MS C runtime:
477
478 1) Arguments are delimited by white space, which is either a
479 space or a tab.
480
481 2) A string surrounded by double quotation marks is
482 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000483 or pipe characters contained within. A quoted string can be
484 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
486 3) A double quotation mark preceded by a backslash is
487 interpreted as a literal double quotation mark.
488
489 4) Backslashes are interpreted literally, unless they
490 immediately precede a double quotation mark.
491
492 5) If backslashes immediately precede a double quotation mark,
493 every pair of backslashes is interpreted as a literal
494 backslash. If the number of backslashes is odd, the last
495 backslash escapes the next double quotation mark as
496 described in rule 3.
497 """
498
499 # See
500 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
501 result = []
502 needquote = False
503 for arg in seq:
504 bs_buf = []
505
506 # Add a space to separate this argument from the others
507 if result:
508 result.append(' ')
509
Christian Heimesfdab48e2008-01-20 09:06:41 +0000510 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 if needquote:
512 result.append('"')
513
514 for c in arg:
515 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000516 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 bs_buf.append(c)
518 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000519 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 result.append('\\' * len(bs_buf)*2)
521 bs_buf = []
522 result.append('\\"')
523 else:
524 # Normal char
525 if bs_buf:
526 result.extend(bs_buf)
527 bs_buf = []
528 result.append(c)
529
Christian Heimesfdab48e2008-01-20 09:06:41 +0000530 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 if bs_buf:
532 result.extend(bs_buf)
533
534 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000535 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 result.append('"')
537
538 return ''.join(result)
539
540
Brett Cannona23810f2008-05-26 19:04:21 +0000541# Various tools for executing commands and looking at their output and status.
542#
543# NB This only works (and is only relevant) for UNIX.
544
545def getstatusoutput(cmd):
546 """Return (status, output) of executing cmd in a shell.
547
548 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
549 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
550 returned output will contain output or error messages. A trailing newline
551 is stripped from the output. The exit status for the command can be
552 interpreted according to the rules for the C function wait(). Example:
553
554 >>> import subprocess
555 >>> subprocess.getstatusoutput('ls /bin/ls')
556 (0, '/bin/ls')
557 >>> subprocess.getstatusoutput('cat /bin/junk')
558 (256, 'cat: /bin/junk: No such file or directory')
559 >>> subprocess.getstatusoutput('/bin/junk')
560 (256, 'sh: /bin/junk: not found')
561 """
562 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
563 text = pipe.read()
564 sts = pipe.close()
565 if sts is None: sts = 0
566 if text[-1:] == '\n': text = text[:-1]
567 return sts, text
568
569
570def getoutput(cmd):
571 """Return output (stdout or stderr) of executing cmd in a shell.
572
573 Like getstatusoutput(), except the exit status is ignored and the return
574 value is a string containing the command's output. Example:
575
576 >>> import subprocess
577 >>> subprocess.getoutput('ls /bin/ls')
578 '/bin/ls'
579 """
580 return getstatusoutput(cmd)[1]
581
582
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583class Popen(object):
584 def __init__(self, args, bufsize=0, executable=None,
585 stdin=None, stdout=None, stderr=None,
586 preexec_fn=None, close_fds=False, shell=False,
587 cwd=None, env=None, universal_newlines=False,
588 startupinfo=None, creationflags=0):
589 """Create new Popen instance."""
590 _cleanup()
591
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000593 if bufsize is None:
594 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000595 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000596 raise TypeError("bufsize must be an integer")
597
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000599 if preexec_fn is not None:
600 raise ValueError("preexec_fn is not supported on Windows "
601 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000602 if close_fds and (stdin is not None or stdout is not None or
603 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000604 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000605 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 else:
607 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000608 if startupinfo is not None:
609 raise ValueError("startupinfo is only supported on Windows "
610 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000612 raise ValueError("creationflags is only supported on Windows "
613 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614
Tim Peterse718f612004-10-12 21:51:32 +0000615 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 self.stdout = None
617 self.stderr = None
618 self.pid = None
619 self.returncode = None
620 self.universal_newlines = universal_newlines
621
622 # Input and output objects. The general principle is like
623 # this:
624 #
625 # Parent Child
626 # ------ -----
627 # p2cwrite ---stdin---> p2cread
628 # c2pread <--stdout--- c2pwrite
629 # errread <--stderr--- errwrite
630 #
631 # On POSIX, the child objects are file descriptors. On
632 # Windows, these are Windows file handles. The parent objects
633 # are file descriptors on both platforms. The parent objects
634 # are None when not using PIPEs. The child objects are None
635 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000636
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637 (p2cread, p2cwrite,
638 c2pread, c2pwrite,
639 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
640
641 self._execute_child(args, executable, preexec_fn, close_fds,
642 cwd, env, universal_newlines,
643 startupinfo, creationflags, shell,
644 p2cread, p2cwrite,
645 c2pread, c2pwrite,
646 errread, errwrite)
647
Thomas Wouterscf297e42007-02-23 15:07:44 +0000648 if mswindows:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000649 if p2cwrite is not None:
650 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
651 if c2pread is not None:
652 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
653 if errread is not None:
654 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000655
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000656 if bufsize == 0:
657 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000658 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000659 self.stdin = io.open(p2cwrite, 'wb', bufsize)
660 if self.universal_newlines:
661 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000662 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000663 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000665 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000666 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000667 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000669 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671
Guido van Rossum98297ee2007-11-06 21:34:58 +0000672 def _translate_newlines(self, data, encoding):
673 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
674 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Guido van Rossumd8faa362007-04-27 19:54:29 +0000677 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 if not self._child_created:
679 # We didn't get to successfully create a child process.
680 return
681 # In case the child hasn't been waited on, check if it's done.
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000682 self._internal_poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000683 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000684 # Child is still running, keep us alive until we can wait on it.
685 _active.append(self)
686
687
Peter Astrand23109f02005-03-03 20:28:59 +0000688 def communicate(self, input=None):
689 """Interact with process: Send data to stdin. Read data from
690 stdout and stderr, until end-of-file is reached. Wait for
691 process to terminate. The optional input argument should be a
692 string to be sent to the child process, or None, if no data
693 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000694
Peter Astrand23109f02005-03-03 20:28:59 +0000695 communicate() returns a tuple (stdout, stderr)."""
696
697 # Optimization: If we are only using one pipe, or no pipe at
698 # all, using select() or threads is unnecessary.
699 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000700 stdout = None
701 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000702 if self.stdin:
703 if input:
704 self.stdin.write(input)
705 self.stdin.close()
706 elif self.stdout:
707 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000708 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000709 elif self.stderr:
710 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000711 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000712 self.wait()
713 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000714
Peter Astrand23109f02005-03-03 20:28:59 +0000715 return self._communicate(input)
716
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000718 def poll(self):
719 return self._internal_poll()
720
721
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 if mswindows:
723 #
724 # Windows methods
725 #
726 def _get_handles(self, stdin, stdout, stderr):
727 """Construct and return tupel with IO objects:
728 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
729 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000730 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000732
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 p2cread, p2cwrite = None, None
734 c2pread, c2pwrite = None, None
735 errread, errwrite = None, None
736
Peter Astrandd38ddf42005-02-10 08:32:50 +0000737 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000739 if p2cread is None:
740 p2cread, _ = CreatePipe(None, 0)
741 elif stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 p2cread, p2cwrite = CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000743 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 p2cread = msvcrt.get_osfhandle(stdin)
745 else:
746 # Assuming file-like object
747 p2cread = msvcrt.get_osfhandle(stdin.fileno())
748 p2cread = self._make_inheritable(p2cread)
749
Peter Astrandd38ddf42005-02-10 08:32:50 +0000750 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000751 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000752 if c2pwrite is None:
753 _, c2pwrite = CreatePipe(None, 0)
754 elif stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 c2pread, c2pwrite = CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000756 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 c2pwrite = msvcrt.get_osfhandle(stdout)
758 else:
759 # Assuming file-like object
760 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
761 c2pwrite = self._make_inheritable(c2pwrite)
762
Peter Astrandd38ddf42005-02-10 08:32:50 +0000763 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000765 if errwrite is None:
766 _, errwrite = CreatePipe(None, 0)
767 elif stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768 errread, errwrite = CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769 elif stderr == STDOUT:
770 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000771 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 errwrite = msvcrt.get_osfhandle(stderr)
773 else:
774 # Assuming file-like object
775 errwrite = msvcrt.get_osfhandle(stderr.fileno())
776 errwrite = self._make_inheritable(errwrite)
777
778 return (p2cread, p2cwrite,
779 c2pread, c2pwrite,
780 errread, errwrite)
781
782
783 def _make_inheritable(self, handle):
784 """Return a duplicate of handle, which is inheritable"""
785 return DuplicateHandle(GetCurrentProcess(), handle,
786 GetCurrentProcess(), 0, 1,
787 DUPLICATE_SAME_ACCESS)
788
789
790 def _find_w9xpopen(self):
791 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000792 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
793 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 if not os.path.exists(w9xpopen):
795 # Eeek - file-not-found - possibly an embedding
796 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000797 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
798 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000800 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
801 "needed for Popen to work with your "
802 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000803 return w9xpopen
804
Tim Peterse718f612004-10-12 21:51:32 +0000805
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000806 def _execute_child(self, args, executable, preexec_fn, close_fds,
807 cwd, env, universal_newlines,
808 startupinfo, creationflags, shell,
809 p2cread, p2cwrite,
810 c2pread, c2pwrite,
811 errread, errwrite):
812 """Execute program (MS Windows version)"""
813
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000814 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 args = list2cmdline(args)
816
Peter Astrandc1d65362004-11-07 14:30:34 +0000817 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000818 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000819 startupinfo = STARTUPINFO()
820 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000821 startupinfo.dwFlags |= STARTF_USESTDHANDLES
822 startupinfo.hStdInput = p2cread
823 startupinfo.hStdOutput = c2pwrite
824 startupinfo.hStdError = errwrite
825
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000827 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
828 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 comspec = os.environ.get("COMSPEC", "cmd.exe")
830 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000831 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000832 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833 # Win9x, or using command.com on NT. We need to
834 # use the w9xpopen intermediate program. For more
835 # information, see KB Q150956
836 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
837 w9xpopen = self._find_w9xpopen()
838 args = '"%s" %s' % (w9xpopen, args)
839 # Not passing CREATE_NEW_CONSOLE has been known to
840 # cause random failures on win9x. Specifically a
841 # dialog: "Your program accessed mem currently in
842 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000843 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 # kill children.
845 creationflags |= CREATE_NEW_CONSOLE
846
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 # Start the process
848 try:
849 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000850 # no special security
851 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000852 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000853 creationflags,
854 env,
855 cwd,
856 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000857 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 # Translate pywintypes.error to WindowsError, which is
859 # a subclass of OSError. FIXME: We should really
860 # translate errno using _sys_errlist (or simliar), but
861 # how can this be done from Python?
862 raise WindowsError(*e.args)
863
864 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000865 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 self._handle = hp
867 self.pid = pid
868 ht.Close()
869
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000870 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871 # handles that only the child should have open. You need
872 # to make sure that no handles to the write end of the
873 # output pipe are maintained in this process or else the
874 # pipe will not close when the child process exits and the
875 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000876 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000878 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000880 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 errwrite.Close()
882
Tim Peterse718f612004-10-12 21:51:32 +0000883
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000884 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885 """Check if child process has terminated. Returns returncode
886 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000887 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
889 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 return self.returncode
891
892
893 def wait(self):
894 """Wait for child process to terminate. Returns returncode
895 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000896 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897 obj = WaitForSingleObject(self._handle, INFINITE)
898 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000899 return self.returncode
900
901
902 def _readerthread(self, fh, buffer):
903 buffer.append(fh.read())
904
905
Peter Astrand23109f02005-03-03 20:28:59 +0000906 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907 stdout = None # Return
908 stderr = None # Return
909
910 if self.stdout:
911 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000912 stdout_thread = threading.Thread(target=self._readerthread,
913 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000914 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 stdout_thread.start()
916 if self.stderr:
917 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000918 stderr_thread = threading.Thread(target=self._readerthread,
919 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000920 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921 stderr_thread.start()
922
923 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000924 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000925 self.stdin.write(input)
926 self.stdin.close()
927
928 if self.stdout:
929 stdout_thread.join()
930 if self.stderr:
931 stderr_thread.join()
932
933 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000934 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000936 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937 stderr = stderr[0]
938
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000939 self.wait()
940 return (stdout, stderr)
941
Christian Heimesa342c012008-04-20 21:01:16 +0000942 def send_signal(self, sig):
943 """Send a signal to the process
944 """
945 if sig == signal.SIGTERM:
946 self.terminate()
947 else:
948 raise ValueError("Only SIGTERM is supported on Windows")
949
950 def terminate(self):
951 """Terminates the process
952 """
953 TerminateProcess(self._handle, 1)
954
955 kill = terminate
956
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 else:
958 #
959 # POSIX methods
960 #
961 def _get_handles(self, stdin, stdout, stderr):
962 """Construct and return tupel with IO objects:
963 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
964 """
965 p2cread, p2cwrite = None, None
966 c2pread, c2pwrite = None, None
967 errread, errwrite = None, None
968
Peter Astrandd38ddf42005-02-10 08:32:50 +0000969 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970 pass
971 elif stdin == PIPE:
972 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000973 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 p2cread = stdin
975 else:
976 # Assuming file-like object
977 p2cread = stdin.fileno()
978
Peter Astrandd38ddf42005-02-10 08:32:50 +0000979 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 pass
981 elif stdout == PIPE:
982 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000983 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984 c2pwrite = stdout
985 else:
986 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000987 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988
Peter Astrandd38ddf42005-02-10 08:32:50 +0000989 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 pass
991 elif stderr == PIPE:
992 errread, errwrite = os.pipe()
993 elif stderr == STDOUT:
994 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000995 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 errwrite = stderr
997 else:
998 # Assuming file-like object
999 errwrite = stderr.fileno()
1000
1001 return (p2cread, p2cwrite,
1002 c2pread, c2pwrite,
1003 errread, errwrite)
1004
1005
1006 def _set_cloexec_flag(self, fd):
1007 try:
1008 cloexec_flag = fcntl.FD_CLOEXEC
1009 except AttributeError:
1010 cloexec_flag = 1
1011
1012 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1013 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1014
1015
1016 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001017 os.closerange(3, but)
1018 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001019
1020
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001021 def _execute_child(self, args, executable, preexec_fn, close_fds,
1022 cwd, env, universal_newlines,
1023 startupinfo, creationflags, shell,
1024 p2cread, p2cwrite,
1025 c2pread, c2pwrite,
1026 errread, errwrite):
1027 """Execute program (POSIX version)"""
1028
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001029 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001031 else:
1032 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033
1034 if shell:
1035 args = ["/bin/sh", "-c"] + args
1036
Peter Astrandd38ddf42005-02-10 08:32:50 +00001037 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001038 executable = args[0]
1039
1040 # For transferring possible exec failure from child to parent
1041 # The first char specifies the exception type: 0 means
1042 # OSError, 1 means some other error.
1043 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001044 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001045 try:
Facundo Batista10706e22009-06-19 20:34:30 +00001046 self._set_cloexec_flag(errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047
Facundo Batista10706e22009-06-19 20:34:30 +00001048 gc_was_enabled = gc.isenabled()
1049 # Disable gc to avoid bug where gc -> file_dealloc ->
1050 # write to stderr -> hang. http://bugs.python.org/issue1336
1051 gc.disable()
1052 try:
1053 self.pid = os.fork()
1054 except:
1055 if gc_was_enabled:
1056 gc.enable()
1057 raise
1058 self._child_created = True
1059 if self.pid == 0:
1060 # Child
1061 try:
1062 # Close parent's pipe ends
1063 if p2cwrite is not None:
1064 os.close(p2cwrite)
1065 if c2pread is not None:
1066 os.close(c2pread)
1067 if errread is not None:
1068 os.close(errread)
1069 os.close(errpipe_read)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001070
Facundo Batista10706e22009-06-19 20:34:30 +00001071 # Dup fds for child
1072 if p2cread is not None:
1073 os.dup2(p2cread, 0)
1074 if c2pwrite is not None:
1075 os.dup2(c2pwrite, 1)
1076 if errwrite is not None:
1077 os.dup2(errwrite, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078
Facundo Batista10706e22009-06-19 20:34:30 +00001079 # Close pipe fds. Make sure we don't close the
1080 # same fd more than once, or standard fds.
1081 if p2cread is not None and p2cread not in (0,):
1082 os.close(p2cread)
1083 if c2pwrite is not None and \
1084 c2pwrite not in (p2cread, 1):
1085 os.close(c2pwrite)
1086 if (errwrite is not None and
1087 errwrite not in (p2cread, c2pwrite, 2)):
1088 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089
Facundo Batista10706e22009-06-19 20:34:30 +00001090 # Close all other fds, if asked for
1091 if close_fds:
1092 self._close_fds(but=errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093
Facundo Batista10706e22009-06-19 20:34:30 +00001094 if cwd is not None:
1095 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096
Facundo Batista10706e22009-06-19 20:34:30 +00001097 if preexec_fn:
1098 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099
Facundo Batista10706e22009-06-19 20:34:30 +00001100 if env is None:
1101 os.execvp(executable, args)
1102 else:
1103 os.execvpe(executable, args, env)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104
Facundo Batista10706e22009-06-19 20:34:30 +00001105 except:
1106 exc_type, exc_value, tb = sys.exc_info()
1107 # Save the traceback and attach it to the exception
1108 # object
1109 exc_lines = traceback.format_exception(exc_type,
1110 exc_value,
1111 tb)
1112 exc_value.child_traceback = ''.join(exc_lines)
1113 os.write(errpipe_write, pickle.dumps(exc_value))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114
Facundo Batista10706e22009-06-19 20:34:30 +00001115 # This exitcode won't be reported to applications, so
1116 # it really doesn't matter what we return.
1117 os._exit(255)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001118
Facundo Batista10706e22009-06-19 20:34:30 +00001119 # Parent
1120 if gc_was_enabled:
1121 gc.enable()
1122 finally:
1123 # be sure the FD is closed no matter what
1124 os.close(errpipe_write)
1125
1126 if p2cread is not None and p2cwrite is not None:
1127 os.close(p2cread)
1128 if c2pwrite is not None and c2pread is not None:
1129 os.close(c2pwrite)
1130 if errwrite is not None and errread is not None:
1131 os.close(errwrite)
1132
1133 # Wait for exec to fail or succeed; possibly raising an
1134 # exception (limited to 1 MB)
1135 data = os.read(errpipe_read, 1048576)
1136 finally:
1137 # be sure the FD is closed no matter what
1138 os.close(errpipe_read)
1139
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001140 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001141 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001142 child_exception = pickle.loads(data)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001143 for fd in (p2cwrite, c2pread, errread):
1144 if fd is not None:
1145 os.close(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001146 raise child_exception
1147
1148
1149 def _handle_exitstatus(self, sts):
1150 if os.WIFSIGNALED(sts):
1151 self.returncode = -os.WTERMSIG(sts)
1152 elif os.WIFEXITED(sts):
1153 self.returncode = os.WEXITSTATUS(sts)
1154 else:
1155 # Should never happen
1156 raise RuntimeError("Unknown child exit status!")
1157
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001158
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001159 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001160 """Check if child process has terminated. Returns returncode
1161 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001162 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001163 try:
1164 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1165 if pid == self.pid:
1166 self._handle_exitstatus(sts)
1167 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 if _deadstate is not None:
1169 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001170 return self.returncode
1171
1172
1173 def wait(self):
1174 """Wait for child process to terminate. Returns returncode
1175 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001176 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001177 pid, sts = os.waitpid(self.pid, 0)
1178 self._handle_exitstatus(sts)
1179 return self.returncode
1180
1181
Peter Astrand23109f02005-03-03 20:28:59 +00001182 def _communicate(self, input):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001183 if self.stdin:
1184 # Flush stdio buffer. This might block, if the user has
1185 # been writing to .stdin in an uncontrolled fashion.
1186 self.stdin.flush()
1187 if not input:
1188 self.stdin.close()
1189
1190 if _has_poll:
1191 stdout, stderr = self._communicate_with_poll(input)
1192 else:
1193 stdout, stderr = self._communicate_with_select(input)
1194
1195 # All data exchanged. Translate lists into strings.
1196 if stdout is not None:
1197 stdout = b''.join(stdout)
1198 if stderr is not None:
1199 stderr = b''.join(stderr)
1200
1201 # Translate newlines, if requested.
1202 # This also turns bytes into strings.
1203 if self.universal_newlines:
1204 if stdout is not None:
1205 stdout = self._translate_newlines(stdout,
1206 self.stdout.encoding)
1207 if stderr is not None:
1208 stderr = self._translate_newlines(stderr,
1209 self.stderr.encoding)
1210
1211 self.wait()
1212 return (stdout, stderr)
1213
1214
1215 def _communicate_with_poll(self, input):
1216 stdout = None # Return
1217 stderr = None # Return
1218 fd2file = {}
1219 fd2output = {}
1220
1221 poller = select.poll()
1222 def register_and_append(file_obj, eventmask):
1223 poller.register(file_obj.fileno(), eventmask)
1224 fd2file[file_obj.fileno()] = file_obj
1225
1226 def close_unregister_and_remove(fd):
1227 poller.unregister(fd)
1228 fd2file[fd].close()
1229 fd2file.pop(fd)
1230
1231 if self.stdin and input:
1232 register_and_append(self.stdin, select.POLLOUT)
1233
1234 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1235 if self.stdout:
1236 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1237 fd2output[self.stdout.fileno()] = stdout = []
1238 if self.stderr:
1239 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1240 fd2output[self.stderr.fileno()] = stderr = []
1241
1242 input_offset = 0
1243 while fd2file:
1244 try:
1245 ready = poller.poll()
1246 except select.error as e:
1247 if e.args[0] == errno.EINTR:
1248 continue
1249 raise
1250
1251 # XXX Rewrite these to use non-blocking I/O on the
1252 # file objects; they are no longer using C stdio!
1253
1254 for fd, mode in ready:
1255 if mode & select.POLLOUT:
1256 chunk = input[input_offset : input_offset + _PIPE_BUF]
1257 input_offset += os.write(fd, chunk)
1258 if input_offset >= len(input):
1259 close_unregister_and_remove(fd)
1260 elif mode & select_POLLIN_POLLPRI:
1261 data = os.read(fd, 4096)
1262 if not data:
1263 close_unregister_and_remove(fd)
1264 fd2output[fd].append(data)
1265 else:
1266 # Ignore hang up or errors.
1267 close_unregister_and_remove(fd)
1268
1269 return (stdout, stderr)
1270
1271
1272 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001273 read_set = []
1274 write_set = []
1275 stdout = None # Return
1276 stderr = None # Return
1277
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001278 if self.stdin and input:
1279 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001280 if self.stdout:
1281 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001282 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001283 if self.stderr:
1284 read_set.append(self.stderr)
1285 stderr = []
1286
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001287 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001288 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001289 try:
1290 rlist, wlist, xlist = select.select(read_set, write_set, [])
1291 except select.error as e:
1292 if e.args[0] == errno.EINTR:
1293 continue
1294 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001295
Guido van Rossum98297ee2007-11-06 21:34:58 +00001296 # XXX Rewrite these to use non-blocking I/O on the
1297 # file objects; they are no longer using C stdio!
1298
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001299 if self.stdin in wlist:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001300 chunk = input[input_offset : input_offset + _PIPE_BUF]
Guido van Rossumbae07c92007-10-08 02:46:15 +00001301 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001302 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001303 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001304 self.stdin.close()
1305 write_set.remove(self.stdin)
1306
1307 if self.stdout in rlist:
1308 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001309 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001310 self.stdout.close()
1311 read_set.remove(self.stdout)
1312 stdout.append(data)
1313
1314 if self.stderr in rlist:
1315 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001316 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001317 self.stderr.close()
1318 read_set.remove(self.stderr)
1319 stderr.append(data)
1320
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001321 return (stdout, stderr)
1322
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001323
Christian Heimesa342c012008-04-20 21:01:16 +00001324 def send_signal(self, sig):
1325 """Send a signal to the process
1326 """
1327 os.kill(self.pid, sig)
1328
1329 def terminate(self):
1330 """Terminate the process with SIGTERM
1331 """
1332 self.send_signal(signal.SIGTERM)
1333
1334 def kill(self):
1335 """Kill the process with SIGKILL
1336 """
1337 self.send_signal(signal.SIGKILL)
1338
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001339
1340def _demo_posix():
1341 #
1342 # Example 1: Simple redirection: Get process list
1343 #
1344 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001345 print("Process list:")
1346 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001347
1348 #
1349 # Example 2: Change uid before executing child
1350 #
1351 if os.getuid() == 0:
1352 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1353 p.wait()
1354
1355 #
1356 # Example 3: Connecting several subprocesses
1357 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001358 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001359 p1 = Popen(["dmesg"], stdout=PIPE)
1360 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001361 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001362
1363 #
1364 # Example 4: Catch execution error
1365 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001366 print()
1367 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001368 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001369 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001370 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001371 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001372 print("The file didn't exist. I thought so...")
1373 print("Child traceback:")
1374 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001375 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001376 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001377 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001378 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001379
1380
1381def _demo_windows():
1382 #
1383 # Example 1: Connecting several subprocesses
1384 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001385 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001386 p1 = Popen("set", stdout=PIPE, shell=True)
1387 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001388 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001389
1390 #
1391 # Example 2: Simple execution of program
1392 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001393 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001394 p = Popen("calc")
1395 p.wait()
1396
1397
1398if __name__ == "__main__":
1399 if mswindows:
1400 _demo_windows()
1401 else:
1402 _demo_posix()