blob: b47ebb8aaca59146623d5d8a78b65ba5d4ac1027 [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 Astrandc26516b2005-02-21 08:13:02 +00005# This module should remain compatible with Python 2.2, see PEP 291.
6#
Peter Astrand3a708df2005-09-23 17:37:29 +00007# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008#
Peter Astrand69bf13f2005-02-14 08:56:32 +00009# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +000010# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Raymond Hettinger837dd932004-10-17 16:36:53 +000012r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000013
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000014This module allows you to spawn processes, connect to their
15input/output/error pipes, and obtain their return codes. This module
16intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000017
18os.system
19os.spawn*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020
21Information about how the subprocess module can be used to replace these
22modules and functions can be found below.
23
24
25
26Using the subprocess module
27===========================
28This module defines one class called Popen:
29
30class Popen(args, bufsize=0, executable=None,
31 stdin=None, stdout=None, stderr=None,
32 preexec_fn=None, close_fds=False, shell=False,
33 cwd=None, env=None, universal_newlines=False,
34 startupinfo=None, creationflags=0):
35
36
37Arguments are:
38
39args should be a string, or a sequence of program arguments. The
40program to execute is normally the first item in the args sequence or
41string, but can be explicitly set by using the executable argument.
42
43On UNIX, with shell=False (default): In this case, the Popen class
44uses os.execvp() to execute the child program. args should normally
45be a sequence. A string will be treated as a sequence with the string
46as the only item (the program to execute).
47
48On UNIX, with shell=True: If args is a string, it specifies the
49command string to execute through the shell. If args is a sequence,
50the first item specifies the command string, and any additional items
51will be treated as additional shell arguments.
52
53On Windows: the Popen class uses CreateProcess() to execute the child
54program, which operates on strings. If args is a sequence, it will be
55converted to a string using the list2cmdline method. Please note that
56not all MS Windows applications interpret the command line the same
57way: The list2cmdline is designed for applications using the same
58rules as the MS C runtime.
59
60bufsize, if given, has the same meaning as the corresponding argument
61to the built-in open() function: 0 means unbuffered, 1 means line
62buffered, any other positive value means use a buffer of
63(approximately) that size. A negative bufsize means to use the system
64default, which usually means fully buffered. The default value for
65bufsize is 0 (unbuffered).
66
67stdin, stdout and stderr specify the executed programs' standard
68input, standard output and standard error file handles, respectively.
69Valid values are PIPE, an existing file descriptor (a positive
70integer), an existing file object, and None. PIPE indicates that a
71new pipe to the child should be created. With None, no redirection
72will occur; the child's file handles will be inherited from the
73parent. Additionally, stderr can be STDOUT, which indicates that the
74stderr data from the applications should be captured into the same
75file handle as for stdout.
76
77If preexec_fn is set to a callable object, this object will be called
78in the child process just before the child is executed.
79
80If close_fds is true, all file descriptors except 0, 1 and 2 will be
81closed before the child process is executed.
82
83if shell is true, the specified command will be executed through the
84shell.
85
86If cwd is not None, the current directory will be changed to cwd
87before the child is executed.
88
89If env is not None, it defines the environment variables for the new
90process.
91
92If universal_newlines is true, the file objects stdout and stderr are
93opened as a text files, but lines may be terminated by any of '\n',
94the Unix end-of-line convention, '\r', the Macintosh convention or
95'\r\n', the Windows convention. All of these external representations
96are seen as '\n' by the Python program. Note: This feature is only
97available if Python is built with universal newline support (the
98default). Also, the newlines attribute of the file objects stdout,
99stdin and stderr are not updated by the communicate() method.
100
101The startupinfo and creationflags, if given, will be passed to the
102underlying CreateProcess() function. They can specify things such as
103appearance of the main window and priority for the new process.
104(Windows only)
105
106
Georg Brandlf9734072008-12-07 15:30:06 +0000107This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108
Peter Astrand5f5e1412004-12-05 20:15:36 +0000109call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 Run command with arguments. Wait for command to complete, then
111 return the returncode attribute.
112
113 The arguments are the same as for the Popen constructor. Example:
114
115 retcode = call(["ls", "-l"])
116
Peter Astrand454f7672005-01-01 09:36:35 +0000117check_call(*popenargs, **kwargs):
118 Run command with arguments. Wait for command to complete. If the
119 exit code was zero then return, otherwise raise
120 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000122
123 The arguments are the same as for the Popen constructor. Example:
124
125 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126
Brett Cannona23810f2008-05-26 19:04:21 +0000127getstatusoutput(cmd):
128 Return (status, output) of executing cmd in a shell.
129
130 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
131 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
132 returned output will contain output or error messages. A trailing newline
133 is stripped from the output. The exit status for the command can be
134 interpreted according to the rules for the C function wait(). Example:
135
136 >>> import subprocess
137 >>> subprocess.getstatusoutput('ls /bin/ls')
138 (0, '/bin/ls')
139 >>> subprocess.getstatusoutput('cat /bin/junk')
140 (256, 'cat: /bin/junk: No such file or directory')
141 >>> subprocess.getstatusoutput('/bin/junk')
142 (256, 'sh: /bin/junk: not found')
143
144getoutput(cmd):
145 Return output (stdout or stderr) of executing cmd in a shell.
146
147 Like getstatusoutput(), except the exit status is ignored and the return
148 value is a string containing the command's output. Example:
149
150 >>> import subprocess
151 >>> subprocess.getoutput('ls /bin/ls')
152 '/bin/ls'
153
Georg Brandlf9734072008-12-07 15:30:06 +0000154check_output(*popenargs, **kwargs):
155 Run command with arguments and return its output as a byte string.
156
157 If the exit code was non-zero it raises a CalledProcessError. The
158 CalledProcessError object will have the return code in the returncode
159 attribute and output in the output attribute.
160
161 The arguments are the same as for the Popen constructor. Example:
162
163 output = subprocess.check_output(["ls", "-l", "/dev/null"])
164
Brett Cannona23810f2008-05-26 19:04:21 +0000165
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166Exceptions
167----------
168Exceptions raised in the child process, before the new program has
169started to execute, will be re-raised in the parent. Additionally,
170the exception object will have one extra attribute called
171'child_traceback', which is a string containing traceback information
172from the childs point of view.
173
174The most common exception raised is OSError. This occurs, for
175example, when trying to execute a non-existent file. Applications
176should prepare for OSErrors.
177
178A ValueError will be raised if Popen is called with invalid arguments.
179
Georg Brandlf9734072008-12-07 15:30:06 +0000180check_call() and check_output() will raise CalledProcessError, if the
181called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000182
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183
184Security
185--------
186Unlike some other popen functions, this implementation will never call
187/bin/sh implicitly. This means that all characters, including shell
188metacharacters, can safely be passed to child processes.
189
190
191Popen objects
192=============
193Instances of the Popen class have the following methods:
194
195poll()
196 Check if child process has terminated. Returns returncode
197 attribute.
198
199wait()
200 Wait for child process to terminate. Returns returncode attribute.
201
202communicate(input=None)
203 Interact with process: Send data to stdin. Read data from stdout
204 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000205 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206 sent to the child process, or None, if no data should be sent to
207 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000208
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 communicate() returns a tuple (stdout, stderr).
210
211 Note: The data read is buffered in memory, so do not use this
212 method if the data size is large or unlimited.
213
214The following attributes are also available:
215
216stdin
217 If the stdin argument is PIPE, this attribute is a file object
218 that provides input to the child process. Otherwise, it is None.
219
220stdout
221 If the stdout argument is PIPE, this attribute is a file object
222 that provides output from the child process. Otherwise, it is
223 None.
224
225stderr
226 If the stderr argument is PIPE, this attribute is file object that
227 provides error output from the child process. Otherwise, it is
228 None.
229
230pid
231 The process ID of the child process.
232
233returncode
234 The child return code. A None value indicates that the process
235 hasn't terminated yet. A negative value -N indicates that the
236 child was terminated by signal N (UNIX only).
237
238
239Replacing older functions with the subprocess module
240====================================================
241In this section, "a ==> b" means that b can be used as a replacement
242for a.
243
244Note: All functions in this section fail (more or less) silently if
245the executed program cannot be found; this module raises an OSError
246exception.
247
248In the following examples, we assume that the subprocess module is
249imported with "from subprocess import *".
250
251
252Replacing /bin/sh shell backquote
253---------------------------------
254output=`mycmd myarg`
255==>
256output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
257
258
259Replacing shell pipe line
260-------------------------
261output=`dmesg | grep hda`
262==>
263p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000264p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265output = p2.communicate()[0]
266
267
268Replacing os.system()
269---------------------
270sts = os.system("mycmd" + " myarg")
271==>
272p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
275Note:
276
277* Calling the program through the shell is usually not required.
278
279* It's easier to look at the returncode attribute than the
280 exitstatus.
281
282A more real-world example would look like this:
283
284try:
285 retcode = call("mycmd" + " myarg", shell=True)
286 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000287 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000289 print("Child returned", retcode, file=sys.stderr)
290except OSError as e:
291 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293
294Replacing os.spawn*
295-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000296P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297
298pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
299==>
300pid = Popen(["/bin/mycmd", "myarg"]).pid
301
302
303P_WAIT example:
304
305retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
306==>
307retcode = call(["/bin/mycmd", "myarg"])
308
309
Tim Peterse718f612004-10-12 21:51:32 +0000310Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311
312os.spawnvp(os.P_NOWAIT, path, args)
313==>
314Popen([path] + args[1:])
315
316
Tim Peterse718f612004-10-12 21:51:32 +0000317Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318
319os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
320==>
321Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322"""
323
324import sys
325mswindows = (sys.platform == "win32")
326
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000327import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000330import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000331import signal
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
Peter Astrand454f7672005-01-01 09:36:35 +0000333# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000334class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000335 """This exception is raised when a process run by check_call() or
336 check_output() returns a non-zero exit status.
337 The exit status will be stored in the returncode attribute;
338 check_output() will also store the output in the output attribute.
339 """
340 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000341 self.returncode = returncode
342 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000343 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000344 def __str__(self):
345 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
346
Peter Astrand454f7672005-01-01 09:36:35 +0000347
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000348if mswindows:
349 import threading
350 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000351 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000352 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000353 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
354 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
355 from win32api import GetCurrentProcess, DuplicateHandle, \
356 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000357 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000359 from win32process import CreateProcess, STARTUPINFO, \
360 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000361 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Christian Heimesa342c012008-04-20 21:01:16 +0000362 from win32process import TerminateProcess
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000364 else:
365 from _subprocess import *
366 class STARTUPINFO:
367 dwFlags = 0
368 hStdInput = None
369 hStdOutput = None
370 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000371 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000372 class pywintypes:
373 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374else:
375 import select
376 import errno
377 import fcntl
378 import pickle
379
Brett Cannona23810f2008-05-26 19:04:21 +0000380__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000381 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382
383try:
384 MAXFD = os.sysconf("SC_OPEN_MAX")
385except:
386 MAXFD = 256
387
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388_active = []
389
390def _cleanup():
391 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000392 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000393 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000394 try:
395 _active.remove(inst)
396 except ValueError:
397 # This can happen if two threads create a new Popen instance.
398 # It's harmless that it was already removed, so ignore.
399 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400
401PIPE = -1
402STDOUT = -2
403
404
Peter Astrand5f5e1412004-12-05 20:15:36 +0000405def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 """Run command with arguments. Wait for command to complete, then
407 return the returncode attribute.
408
409 The arguments are the same as for the Popen constructor. Example:
410
411 retcode = call(["ls", "-l"])
412 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000413 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414
415
Peter Astrand454f7672005-01-01 09:36:35 +0000416def check_call(*popenargs, **kwargs):
417 """Run command with arguments. Wait for command to complete. If
418 the exit code was zero then return, otherwise raise
419 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000420 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000421
422 The arguments are the same as for the Popen constructor. Example:
423
424 check_call(["ls", "-l"])
425 """
426 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000427 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000428 cmd = kwargs.get("args")
429 if cmd is None:
430 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000431 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000432 return 0
433
434
435def check_output(*popenargs, **kwargs):
436 """Run command with arguments and return its output as a byte string.
437
438 If the exit code was non-zero it raises a CalledProcessError. The
439 CalledProcessError object will have the return code in the returncode
440 attribute and output in the output attribute.
441
442 The arguments are the same as for the Popen constructor. Example:
443
444 >>> check_output(["ls", "-l", "/dev/null"])
445 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
446
447 The stdout argument is not allowed as it is used internally.
448 To capture standard error in the result, use stderr=subprocess.STDOUT.
449
450 >>> check_output(["/bin/sh", "-c",
451 "ls -l non_existant_file ; exit 0"],
452 stderr=subprocess.STDOUT)
453 'ls: non_existant_file: No such file or directory\n'
454 """
455 if 'stdout' in kwargs:
456 raise ValueError('stdout argument not allowed, it will be overridden.')
457 process = Popen(*popenargs, stdout=PIPE, **kwargs)
458 output, unused_err = process.communicate()
459 retcode = process.poll()
460 if retcode:
461 cmd = kwargs.get("args")
462 if cmd is None:
463 cmd = popenargs[0]
464 raise CalledProcessError(retcode, cmd, output=output)
465 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000466
467
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468def list2cmdline(seq):
469 """
470 Translate a sequence of arguments into a command line
471 string, using the same rules as the MS C runtime:
472
473 1) Arguments are delimited by white space, which is either a
474 space or a tab.
475
476 2) A string surrounded by double quotation marks is
477 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000478 or pipe characters contained within. A quoted string can be
479 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480
481 3) A double quotation mark preceded by a backslash is
482 interpreted as a literal double quotation mark.
483
484 4) Backslashes are interpreted literally, unless they
485 immediately precede a double quotation mark.
486
487 5) If backslashes immediately precede a double quotation mark,
488 every pair of backslashes is interpreted as a literal
489 backslash. If the number of backslashes is odd, the last
490 backslash escapes the next double quotation mark as
491 described in rule 3.
492 """
493
494 # See
495 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
496 result = []
497 needquote = False
498 for arg in seq:
499 bs_buf = []
500
501 # Add a space to separate this argument from the others
502 if result:
503 result.append(' ')
504
Christian Heimesfdab48e2008-01-20 09:06:41 +0000505 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 if needquote:
507 result.append('"')
508
509 for c in arg:
510 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000511 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 bs_buf.append(c)
513 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000514 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 result.append('\\' * len(bs_buf)*2)
516 bs_buf = []
517 result.append('\\"')
518 else:
519 # Normal char
520 if bs_buf:
521 result.extend(bs_buf)
522 bs_buf = []
523 result.append(c)
524
Christian Heimesfdab48e2008-01-20 09:06:41 +0000525 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 if bs_buf:
527 result.extend(bs_buf)
528
529 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000530 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 result.append('"')
532
533 return ''.join(result)
534
535
Brett Cannona23810f2008-05-26 19:04:21 +0000536# Various tools for executing commands and looking at their output and status.
537#
538# NB This only works (and is only relevant) for UNIX.
539
540def getstatusoutput(cmd):
541 """Return (status, output) of executing cmd in a shell.
542
543 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
544 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
545 returned output will contain output or error messages. A trailing newline
546 is stripped from the output. The exit status for the command can be
547 interpreted according to the rules for the C function wait(). Example:
548
549 >>> import subprocess
550 >>> subprocess.getstatusoutput('ls /bin/ls')
551 (0, '/bin/ls')
552 >>> subprocess.getstatusoutput('cat /bin/junk')
553 (256, 'cat: /bin/junk: No such file or directory')
554 >>> subprocess.getstatusoutput('/bin/junk')
555 (256, 'sh: /bin/junk: not found')
556 """
557 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
558 text = pipe.read()
559 sts = pipe.close()
560 if sts is None: sts = 0
561 if text[-1:] == '\n': text = text[:-1]
562 return sts, text
563
564
565def getoutput(cmd):
566 """Return output (stdout or stderr) of executing cmd in a shell.
567
568 Like getstatusoutput(), except the exit status is ignored and the return
569 value is a string containing the command's output. Example:
570
571 >>> import subprocess
572 >>> subprocess.getoutput('ls /bin/ls')
573 '/bin/ls'
574 """
575 return getstatusoutput(cmd)[1]
576
577
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578class Popen(object):
579 def __init__(self, args, bufsize=0, executable=None,
580 stdin=None, stdout=None, stderr=None,
581 preexec_fn=None, close_fds=False, shell=False,
582 cwd=None, env=None, universal_newlines=False,
583 startupinfo=None, creationflags=0):
584 """Create new Popen instance."""
585 _cleanup()
586
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000587 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000588 if bufsize is None:
589 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000590 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000591 raise TypeError("bufsize must be an integer")
592
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000594 if preexec_fn is not None:
595 raise ValueError("preexec_fn is not supported on Windows "
596 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000597 if close_fds and (stdin is not None or stdout is not None or
598 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000599 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000600 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 else:
602 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000603 if startupinfo is not None:
604 raise ValueError("startupinfo is only supported on Windows "
605 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000607 raise ValueError("creationflags is only supported on Windows "
608 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609
Tim Peterse718f612004-10-12 21:51:32 +0000610 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 self.stdout = None
612 self.stderr = None
613 self.pid = None
614 self.returncode = None
615 self.universal_newlines = universal_newlines
616
617 # Input and output objects. The general principle is like
618 # this:
619 #
620 # Parent Child
621 # ------ -----
622 # p2cwrite ---stdin---> p2cread
623 # c2pread <--stdout--- c2pwrite
624 # errread <--stderr--- errwrite
625 #
626 # On POSIX, the child objects are file descriptors. On
627 # Windows, these are Windows file handles. The parent objects
628 # are file descriptors on both platforms. The parent objects
629 # are None when not using PIPEs. The child objects are None
630 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000631
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 (p2cread, p2cwrite,
633 c2pread, c2pwrite,
634 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
635
636 self._execute_child(args, executable, preexec_fn, close_fds,
637 cwd, env, universal_newlines,
638 startupinfo, creationflags, shell,
639 p2cread, p2cwrite,
640 c2pread, c2pwrite,
641 errread, errwrite)
642
Thomas Wouterscf297e42007-02-23 15:07:44 +0000643 # On Windows, you cannot just redirect one or two handles: You
644 # either have to redirect all three or none. If the subprocess
645 # user has only redirected one or two handles, we are
646 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000647 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000648 if mswindows:
649 if stdin is None and p2cwrite is not None:
650 os.close(p2cwrite)
651 p2cwrite = None
652 if stdout is None and c2pread is not None:
653 os.close(c2pread)
654 c2pread = None
655 if stderr is None and errread is not None:
656 os.close(errread)
657 errread = None
658
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000659 if bufsize == 0:
660 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000661 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000662 self.stdin = io.open(p2cwrite, 'wb', bufsize)
663 if self.universal_newlines:
664 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000665 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000666 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000668 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000669 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000670 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000672 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000673
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674
Guido van Rossum98297ee2007-11-06 21:34:58 +0000675 def _translate_newlines(self, data, encoding):
676 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
677 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000679
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000681 if not self._child_created:
682 # We didn't get to successfully create a child process.
683 return
684 # In case the child hasn't been waited on, check if it's done.
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000685 self._internal_poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000686 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000687 # Child is still running, keep us alive until we can wait on it.
688 _active.append(self)
689
690
Peter Astrand23109f02005-03-03 20:28:59 +0000691 def communicate(self, input=None):
692 """Interact with process: Send data to stdin. Read data from
693 stdout and stderr, until end-of-file is reached. Wait for
694 process to terminate. The optional input argument should be a
695 string to be sent to the child process, or None, if no data
696 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000697
Peter Astrand23109f02005-03-03 20:28:59 +0000698 communicate() returns a tuple (stdout, stderr)."""
699
700 # Optimization: If we are only using one pipe, or no pipe at
701 # all, using select() or threads is unnecessary.
702 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000703 stdout = None
704 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000705 if self.stdin:
706 if input:
707 self.stdin.write(input)
708 self.stdin.close()
709 elif self.stdout:
710 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000711 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000712 elif self.stderr:
713 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000714 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000715 self.wait()
716 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000717
Peter Astrand23109f02005-03-03 20:28:59 +0000718 return self._communicate(input)
719
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000721 def poll(self):
722 return self._internal_poll()
723
724
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725 if mswindows:
726 #
727 # Windows methods
728 #
729 def _get_handles(self, stdin, stdout, stderr):
730 """Construct and return tupel with IO objects:
731 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
732 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000733 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000735
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736 p2cread, p2cwrite = None, None
737 c2pread, c2pwrite = None, None
738 errread, errwrite = None, None
739
Peter Astrandd38ddf42005-02-10 08:32:50 +0000740 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000742 if p2cread is not None:
743 pass
744 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745 p2cread, p2cwrite = CreatePipe(None, 0)
746 # Detach and turn into fd
747 p2cwrite = p2cwrite.Detach()
748 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000749 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750 p2cread = msvcrt.get_osfhandle(stdin)
751 else:
752 # Assuming file-like object
753 p2cread = msvcrt.get_osfhandle(stdin.fileno())
754 p2cread = self._make_inheritable(p2cread)
755
Peter Astrandd38ddf42005-02-10 08:32:50 +0000756 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000758 if c2pwrite is not None:
759 pass
760 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 c2pread, c2pwrite = CreatePipe(None, 0)
762 # Detach and turn into fd
763 c2pread = c2pread.Detach()
764 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000765 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 c2pwrite = msvcrt.get_osfhandle(stdout)
767 else:
768 # Assuming file-like object
769 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
770 c2pwrite = self._make_inheritable(c2pwrite)
771
Peter Astrandd38ddf42005-02-10 08:32:50 +0000772 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000774 if errwrite is not None:
775 pass
776 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 errread, errwrite = CreatePipe(None, 0)
778 # Detach and turn into fd
779 errread = errread.Detach()
780 errread = msvcrt.open_osfhandle(errread, 0)
781 elif stderr == STDOUT:
782 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000783 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000784 errwrite = msvcrt.get_osfhandle(stderr)
785 else:
786 # Assuming file-like object
787 errwrite = msvcrt.get_osfhandle(stderr.fileno())
788 errwrite = self._make_inheritable(errwrite)
789
790 return (p2cread, p2cwrite,
791 c2pread, c2pwrite,
792 errread, errwrite)
793
794
795 def _make_inheritable(self, handle):
796 """Return a duplicate of handle, which is inheritable"""
797 return DuplicateHandle(GetCurrentProcess(), handle,
798 GetCurrentProcess(), 0, 1,
799 DUPLICATE_SAME_ACCESS)
800
801
802 def _find_w9xpopen(self):
803 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000804 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
805 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000806 if not os.path.exists(w9xpopen):
807 # Eeek - file-not-found - possibly an embedding
808 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000809 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
810 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000812 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
813 "needed for Popen to work with your "
814 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 return w9xpopen
816
Tim Peterse718f612004-10-12 21:51:32 +0000817
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818 def _execute_child(self, args, executable, preexec_fn, close_fds,
819 cwd, env, universal_newlines,
820 startupinfo, creationflags, shell,
821 p2cread, p2cwrite,
822 c2pread, c2pwrite,
823 errread, errwrite):
824 """Execute program (MS Windows version)"""
825
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000826 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 args = list2cmdline(args)
828
Peter Astrandc1d65362004-11-07 14:30:34 +0000829 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000830 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000831 startupinfo = STARTUPINFO()
832 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000833 startupinfo.dwFlags |= STARTF_USESTDHANDLES
834 startupinfo.hStdInput = p2cread
835 startupinfo.hStdOutput = c2pwrite
836 startupinfo.hStdError = errwrite
837
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000839 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
840 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 comspec = os.environ.get("COMSPEC", "cmd.exe")
842 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000843 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000844 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 # Win9x, or using command.com on NT. We need to
846 # use the w9xpopen intermediate program. For more
847 # information, see KB Q150956
848 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
849 w9xpopen = self._find_w9xpopen()
850 args = '"%s" %s' % (w9xpopen, args)
851 # Not passing CREATE_NEW_CONSOLE has been known to
852 # cause random failures on win9x. Specifically a
853 # dialog: "Your program accessed mem currently in
854 # use at xxx" and a hopeful warning about the
855 # stability of your system. Cost is Ctrl+C wont
856 # kill children.
857 creationflags |= CREATE_NEW_CONSOLE
858
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000859 # Start the process
860 try:
861 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000862 # no special security
863 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000864 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000865 creationflags,
866 env,
867 cwd,
868 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000869 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870 # Translate pywintypes.error to WindowsError, which is
871 # a subclass of OSError. FIXME: We should really
872 # translate errno using _sys_errlist (or simliar), but
873 # how can this be done from Python?
874 raise WindowsError(*e.args)
875
876 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000877 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000878 self._handle = hp
879 self.pid = pid
880 ht.Close()
881
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000882 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000883 # handles that only the child should have open. You need
884 # to make sure that no handles to the write end of the
885 # output pipe are maintained in this process or else the
886 # pipe will not close when the child process exits and the
887 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000888 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000890 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000892 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 errwrite.Close()
894
Tim Peterse718f612004-10-12 21:51:32 +0000895
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000896 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897 """Check if child process has terminated. Returns returncode
898 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
901 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902 return self.returncode
903
904
905 def wait(self):
906 """Wait for child process to terminate. Returns returncode
907 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000908 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909 obj = WaitForSingleObject(self._handle, INFINITE)
910 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 return self.returncode
912
913
914 def _readerthread(self, fh, buffer):
915 buffer.append(fh.read())
916
917
Peter Astrand23109f02005-03-03 20:28:59 +0000918 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 stdout = None # Return
920 stderr = None # Return
921
922 if self.stdout:
923 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000924 stdout_thread = threading.Thread(target=self._readerthread,
925 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000926 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927 stdout_thread.start()
928 if self.stderr:
929 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000930 stderr_thread = threading.Thread(target=self._readerthread,
931 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000932 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 stderr_thread.start()
934
935 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000936 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937 self.stdin.write(input)
938 self.stdin.close()
939
940 if self.stdout:
941 stdout_thread.join()
942 if self.stderr:
943 stderr_thread.join()
944
945 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000946 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000948 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949 stderr = stderr[0]
950
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 self.wait()
952 return (stdout, stderr)
953
Christian Heimesa342c012008-04-20 21:01:16 +0000954 def send_signal(self, sig):
955 """Send a signal to the process
956 """
957 if sig == signal.SIGTERM:
958 self.terminate()
959 else:
960 raise ValueError("Only SIGTERM is supported on Windows")
961
962 def terminate(self):
963 """Terminates the process
964 """
965 TerminateProcess(self._handle, 1)
966
967 kill = terminate
968
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969 else:
970 #
971 # POSIX methods
972 #
973 def _get_handles(self, stdin, stdout, stderr):
974 """Construct and return tupel with IO objects:
975 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
976 """
977 p2cread, p2cwrite = None, None
978 c2pread, c2pwrite = None, None
979 errread, errwrite = None, None
980
Peter Astrandd38ddf42005-02-10 08:32:50 +0000981 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 pass
983 elif stdin == PIPE:
984 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000985 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000986 p2cread = stdin
987 else:
988 # Assuming file-like object
989 p2cread = stdin.fileno()
990
Peter Astrandd38ddf42005-02-10 08:32:50 +0000991 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992 pass
993 elif stdout == PIPE:
994 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000995 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 c2pwrite = stdout
997 else:
998 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000999 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000
Peter Astrandd38ddf42005-02-10 08:32:50 +00001001 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 pass
1003 elif stderr == PIPE:
1004 errread, errwrite = os.pipe()
1005 elif stderr == STDOUT:
1006 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001007 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008 errwrite = stderr
1009 else:
1010 # Assuming file-like object
1011 errwrite = stderr.fileno()
1012
1013 return (p2cread, p2cwrite,
1014 c2pread, c2pwrite,
1015 errread, errwrite)
1016
1017
1018 def _set_cloexec_flag(self, fd):
1019 try:
1020 cloexec_flag = fcntl.FD_CLOEXEC
1021 except AttributeError:
1022 cloexec_flag = 1
1023
1024 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1025 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1026
1027
1028 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001029 os.closerange(3, but)
1030 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001031
1032
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033 def _execute_child(self, args, executable, preexec_fn, close_fds,
1034 cwd, env, universal_newlines,
1035 startupinfo, creationflags, shell,
1036 p2cread, p2cwrite,
1037 c2pread, c2pwrite,
1038 errread, errwrite):
1039 """Execute program (POSIX version)"""
1040
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001041 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001042 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043 else:
1044 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001045
1046 if shell:
1047 args = ["/bin/sh", "-c"] + args
1048
Peter Astrandd38ddf42005-02-10 08:32:50 +00001049 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001050 executable = args[0]
1051
1052 # For transferring possible exec failure from child to parent
1053 # The first char specifies the exception type: 0 means
1054 # OSError, 1 means some other error.
1055 errpipe_read, errpipe_write = os.pipe()
1056 self._set_cloexec_flag(errpipe_write)
1057
Christian Heimesfdab48e2008-01-20 09:06:41 +00001058 gc_was_enabled = gc.isenabled()
1059 # Disable gc to avoid bug where gc -> file_dealloc ->
1060 # write to stderr -> hang. http://bugs.python.org/issue1336
1061 gc.disable()
1062 try:
1063 self.pid = os.fork()
1064 except:
1065 if gc_was_enabled:
1066 gc.enable()
1067 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001068 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 if self.pid == 0:
1070 # Child
1071 try:
1072 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +00001073 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001075 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001076 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001077 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078 os.close(errread)
1079 os.close(errpipe_read)
1080
1081 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +00001082 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001084 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001086 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087 os.dup2(errwrite, 2)
1088
Thomas Wouters89f507f2006-12-13 04:49:30 +00001089 # Close pipe fds. Make sure we don't close the same
1090 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +00001091 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001092 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001093 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001094 os.close(c2pwrite)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001095 if (errwrite is not None and
1096 errwrite not in (p2cread, c2pwrite, 2)):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001097 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001098
1099 # Close all other fds, if asked for
1100 if close_fds:
1101 self._close_fds(but=errpipe_write)
1102
Peter Astrandd38ddf42005-02-10 08:32:50 +00001103 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 os.chdir(cwd)
1105
1106 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +00001107 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108
Peter Astrandd38ddf42005-02-10 08:32:50 +00001109 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110 os.execvp(executable, args)
1111 else:
1112 os.execvpe(executable, args, env)
1113
1114 except:
1115 exc_type, exc_value, tb = sys.exc_info()
1116 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001117 exc_lines = traceback.format_exception(exc_type,
1118 exc_value,
1119 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001120 exc_value.child_traceback = ''.join(exc_lines)
1121 os.write(errpipe_write, pickle.dumps(exc_value))
1122
1123 # This exitcode won't be reported to applications, so it
1124 # really doesn't matter what we return.
1125 os._exit(255)
1126
1127 # Parent
Christian Heimesfdab48e2008-01-20 09:06:41 +00001128 if gc_was_enabled:
1129 gc.enable()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001130 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001131 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001132 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001133 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001135 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001136 os.close(errwrite)
1137
1138 # Wait for exec to fail or succeed; possibly raising exception
1139 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1140 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001141 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001142 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001143 child_exception = pickle.loads(data)
1144 raise child_exception
1145
1146
1147 def _handle_exitstatus(self, sts):
1148 if os.WIFSIGNALED(sts):
1149 self.returncode = -os.WTERMSIG(sts)
1150 elif os.WIFEXITED(sts):
1151 self.returncode = os.WEXITSTATUS(sts)
1152 else:
1153 # Should never happen
1154 raise RuntimeError("Unknown child exit status!")
1155
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001156
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001157 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001158 """Check if child process has terminated. Returns returncode
1159 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001160 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161 try:
1162 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1163 if pid == self.pid:
1164 self._handle_exitstatus(sts)
1165 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166 if _deadstate is not None:
1167 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001168 return self.returncode
1169
1170
1171 def wait(self):
1172 """Wait for child process to terminate. Returns returncode
1173 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001174 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175 pid, sts = os.waitpid(self.pid, 0)
1176 self._handle_exitstatus(sts)
1177 return self.returncode
1178
1179
Peter Astrand23109f02005-03-03 20:28:59 +00001180 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001181 read_set = []
1182 write_set = []
1183 stdout = None # Return
1184 stderr = None # Return
1185
1186 if self.stdin:
1187 # Flush stdio buffer. This might block, if the user has
1188 # been writing to .stdin in an uncontrolled fashion.
1189 self.stdin.flush()
1190 if input:
1191 write_set.append(self.stdin)
1192 else:
1193 self.stdin.close()
1194 if self.stdout:
1195 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001196 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001197 if self.stderr:
1198 read_set.append(self.stderr)
1199 stderr = []
1200
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001201 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001202 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001203 try:
1204 rlist, wlist, xlist = select.select(read_set, write_set, [])
1205 except select.error as e:
1206 if e.args[0] == errno.EINTR:
1207 continue
1208 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001209
Guido van Rossum98297ee2007-11-06 21:34:58 +00001210 # XXX Rewrite these to use non-blocking I/O on the
1211 # file objects; they are no longer using C stdio!
1212
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213 if self.stdin in wlist:
1214 # When select has indicated that the file is writable,
1215 # we can write up to PIPE_BUF bytes without risk
1216 # blocking. POSIX defines PIPE_BUF >= 512
Guido van Rossumbae07c92007-10-08 02:46:15 +00001217 chunk = input[input_offset : input_offset + 512]
1218 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001219 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001220 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001221 self.stdin.close()
1222 write_set.remove(self.stdin)
1223
1224 if self.stdout in rlist:
1225 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001226 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001227 self.stdout.close()
1228 read_set.remove(self.stdout)
1229 stdout.append(data)
1230
1231 if self.stderr in rlist:
1232 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001233 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001234 self.stderr.close()
1235 read_set.remove(self.stderr)
1236 stderr.append(data)
1237
1238 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001239 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001240 stdout = b"".join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001241 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001242 stderr = b"".join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001243
Guido van Rossum98297ee2007-11-06 21:34:58 +00001244 # Translate newlines, if requested.
1245 # This also turns bytes into strings.
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001246 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001247 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001248 stdout = self._translate_newlines(stdout,
1249 self.stdout.encoding)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001250 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001251 stderr = self._translate_newlines(stderr,
1252 self.stderr.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001253
1254 self.wait()
1255 return (stdout, stderr)
1256
Christian Heimesa342c012008-04-20 21:01:16 +00001257 def send_signal(self, sig):
1258 """Send a signal to the process
1259 """
1260 os.kill(self.pid, sig)
1261
1262 def terminate(self):
1263 """Terminate the process with SIGTERM
1264 """
1265 self.send_signal(signal.SIGTERM)
1266
1267 def kill(self):
1268 """Kill the process with SIGKILL
1269 """
1270 self.send_signal(signal.SIGKILL)
1271
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001272
1273def _demo_posix():
1274 #
1275 # Example 1: Simple redirection: Get process list
1276 #
1277 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001278 print("Process list:")
1279 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001280
1281 #
1282 # Example 2: Change uid before executing child
1283 #
1284 if os.getuid() == 0:
1285 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1286 p.wait()
1287
1288 #
1289 # Example 3: Connecting several subprocesses
1290 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001291 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001292 p1 = Popen(["dmesg"], stdout=PIPE)
1293 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001294 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001295
1296 #
1297 # Example 4: Catch execution error
1298 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001299 print()
1300 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001301 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001302 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001303 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001304 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001305 print("The file didn't exist. I thought so...")
1306 print("Child traceback:")
1307 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001308 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001309 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001310 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001311 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001312
1313
1314def _demo_windows():
1315 #
1316 # Example 1: Connecting several subprocesses
1317 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001318 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001319 p1 = Popen("set", stdout=PIPE, shell=True)
1320 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001321 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001322
1323 #
1324 # Example 2: Simple execution of program
1325 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001326 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001327 p = Popen("calc")
1328 p.wait()
1329
1330
1331if __name__ == "__main__":
1332 if mswindows:
1333 _demo_windows()
1334 else:
1335 _demo_posix()