blob: d19e5380cb28215cda9a953365e49c4f75e5b278 [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:
Brian Curtine1491662010-04-24 16:33:18 +0000347 from _subprocess import CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000348 import threading
349 import msvcrt
Brian Curtine1491662010-04-24 16:33:18 +0000350 import _subprocess
351 class STARTUPINFO:
352 dwFlags = 0
353 hStdInput = None
354 hStdOutput = None
355 hStdError = None
356 wShowWindow = 0
357 class pywintypes:
358 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359else:
360 import select
Georg Brandlae83d6e2009-08-13 09:04:31 +0000361 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 import errno
363 import fcntl
364 import pickle
365
Gregory P. Smith10d29522009-08-13 18:33:30 +0000366 # When select or poll has indicated that the file is writable,
367 # we can write up to _PIPE_BUF bytes without risk of blocking.
368 # POSIX defines PIPE_BUF as >= 512.
369 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
370
371
Brett Cannona23810f2008-05-26 19:04:21 +0000372__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000373 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374
Brian Curtine1491662010-04-24 16:33:18 +0000375if mswindows:
376 __all__.append("CREATE_NEW_CONSOLE")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000377try:
378 MAXFD = os.sysconf("SC_OPEN_MAX")
379except:
380 MAXFD = 256
381
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382_active = []
383
384def _cleanup():
385 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000386 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000387 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000388 try:
389 _active.remove(inst)
390 except ValueError:
391 # This can happen if two threads create a new Popen instance.
392 # It's harmless that it was already removed, so ignore.
393 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394
395PIPE = -1
396STDOUT = -2
397
398
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000399def _eintr_retry_call(func, *args):
400 while True:
401 try:
402 return func(*args)
403 except OSError as e:
404 if e.errno == errno.EINTR:
405 continue
406 raise
407
408
Peter Astrand5f5e1412004-12-05 20:15:36 +0000409def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410 """Run command with arguments. Wait for command to complete, then
411 return the returncode attribute.
412
413 The arguments are the same as for the Popen constructor. Example:
414
415 retcode = call(["ls", "-l"])
416 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000417 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418
419
Peter Astrand454f7672005-01-01 09:36:35 +0000420def check_call(*popenargs, **kwargs):
421 """Run command with arguments. Wait for command to complete. If
422 the exit code was zero then return, otherwise raise
423 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000424 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000425
426 The arguments are the same as for the Popen constructor. Example:
427
428 check_call(["ls", "-l"])
429 """
430 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000431 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000432 cmd = kwargs.get("args")
433 if cmd is None:
434 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000435 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000436 return 0
437
438
439def check_output(*popenargs, **kwargs):
440 """Run command with arguments and return its output as a byte string.
441
442 If the exit code was non-zero it raises a CalledProcessError. The
443 CalledProcessError object will have the return code in the returncode
444 attribute and output in the output attribute.
445
446 The arguments are the same as for the Popen constructor. Example:
447
448 >>> check_output(["ls", "-l", "/dev/null"])
449 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
450
451 The stdout argument is not allowed as it is used internally.
452 To capture standard error in the result, use stderr=subprocess.STDOUT.
453
454 >>> check_output(["/bin/sh", "-c",
Mark Dickinson934896d2009-02-21 20:59:32 +0000455 "ls -l non_existent_file ; exit 0"],
Georg Brandlf9734072008-12-07 15:30:06 +0000456 stderr=subprocess.STDOUT)
Mark Dickinson934896d2009-02-21 20:59:32 +0000457 'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000458 """
459 if 'stdout' in kwargs:
460 raise ValueError('stdout argument not allowed, it will be overridden.')
461 process = Popen(*popenargs, stdout=PIPE, **kwargs)
462 output, unused_err = process.communicate()
463 retcode = process.poll()
464 if retcode:
465 cmd = kwargs.get("args")
466 if cmd is None:
467 cmd = popenargs[0]
468 raise CalledProcessError(retcode, cmd, output=output)
469 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000470
471
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472def list2cmdline(seq):
473 """
474 Translate a sequence of arguments into a command line
475 string, using the same rules as the MS C runtime:
476
477 1) Arguments are delimited by white space, which is either a
478 space or a tab.
479
480 2) A string surrounded by double quotation marks is
481 interpreted as a single argument, regardless of white space
Jean-Paul Calderone2323d202010-06-18 20:11:43 +0000482 contained within. A quoted string can be embedded in an
483 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484
485 3) A double quotation mark preceded by a backslash is
486 interpreted as a literal double quotation mark.
487
488 4) Backslashes are interpreted literally, unless they
489 immediately precede a double quotation mark.
490
491 5) If backslashes immediately precede a double quotation mark,
492 every pair of backslashes is interpreted as a literal
493 backslash. If the number of backslashes is odd, the last
494 backslash escapes the next double quotation mark as
495 described in rule 3.
496 """
497
498 # See
Eric Smith536d2992009-11-09 15:24:55 +0000499 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
500 # or search http://msdn.microsoft.com for
501 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 result = []
503 needquote = False
504 for arg in seq:
505 bs_buf = []
506
507 # Add a space to separate this argument from the others
508 if result:
509 result.append(' ')
510
Jean-Paul Calderone2323d202010-06-18 20:11:43 +0000511 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 if needquote:
513 result.append('"')
514
515 for c in arg:
516 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000517 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 bs_buf.append(c)
519 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000520 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 result.append('\\' * len(bs_buf)*2)
522 bs_buf = []
523 result.append('\\"')
524 else:
525 # Normal char
526 if bs_buf:
527 result.extend(bs_buf)
528 bs_buf = []
529 result.append(c)
530
Christian Heimesfdab48e2008-01-20 09:06:41 +0000531 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 if bs_buf:
533 result.extend(bs_buf)
534
535 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000536 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 result.append('"')
538
539 return ''.join(result)
540
541
Brett Cannona23810f2008-05-26 19:04:21 +0000542# Various tools for executing commands and looking at their output and status.
543#
544# NB This only works (and is only relevant) for UNIX.
545
546def getstatusoutput(cmd):
547 """Return (status, output) of executing cmd in a shell.
548
549 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
550 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
551 returned output will contain output or error messages. A trailing newline
552 is stripped from the output. The exit status for the command can be
553 interpreted according to the rules for the C function wait(). Example:
554
555 >>> import subprocess
556 >>> subprocess.getstatusoutput('ls /bin/ls')
557 (0, '/bin/ls')
558 >>> subprocess.getstatusoutput('cat /bin/junk')
559 (256, 'cat: /bin/junk: No such file or directory')
560 >>> subprocess.getstatusoutput('/bin/junk')
561 (256, 'sh: /bin/junk: not found')
562 """
563 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
564 text = pipe.read()
565 sts = pipe.close()
566 if sts is None: sts = 0
567 if text[-1:] == '\n': text = text[:-1]
568 return sts, text
569
570
571def getoutput(cmd):
572 """Return output (stdout or stderr) of executing cmd in a shell.
573
574 Like getstatusoutput(), except the exit status is ignored and the return
575 value is a string containing the command's output. Example:
576
577 >>> import subprocess
578 >>> subprocess.getoutput('ls /bin/ls')
579 '/bin/ls'
580 """
581 return getstatusoutput(cmd)[1]
582
583
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000584class Popen(object):
585 def __init__(self, args, bufsize=0, executable=None,
586 stdin=None, stdout=None, stderr=None,
587 preexec_fn=None, close_fds=False, shell=False,
588 cwd=None, env=None, universal_newlines=False,
589 startupinfo=None, creationflags=0):
590 """Create new Popen instance."""
591 _cleanup()
592
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000593 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000594 if bufsize is None:
595 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000596 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000597 raise TypeError("bufsize must be an integer")
598
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000600 if preexec_fn is not None:
601 raise ValueError("preexec_fn is not supported on Windows "
602 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000603 if close_fds and (stdin is not None or stdout is not None or
604 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000605 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000606 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 else:
608 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000609 if startupinfo is not None:
610 raise ValueError("startupinfo is only supported on Windows "
611 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000613 raise ValueError("creationflags is only supported on Windows "
614 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000615
Tim Peterse718f612004-10-12 21:51:32 +0000616 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 self.stdout = None
618 self.stderr = None
619 self.pid = None
620 self.returncode = None
621 self.universal_newlines = universal_newlines
622
623 # Input and output objects. The general principle is like
624 # this:
625 #
626 # Parent Child
627 # ------ -----
628 # p2cwrite ---stdin---> p2cread
629 # c2pread <--stdout--- c2pwrite
630 # errread <--stderr--- errwrite
631 #
632 # On POSIX, the child objects are file descriptors. On
633 # Windows, these are Windows file handles. The parent objects
634 # are file descriptors on both platforms. The parent objects
635 # are None when not using PIPEs. The child objects are None
636 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000637
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 (p2cread, p2cwrite,
639 c2pread, c2pwrite,
640 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
641
642 self._execute_child(args, executable, preexec_fn, close_fds,
643 cwd, env, universal_newlines,
644 startupinfo, creationflags, shell,
645 p2cread, p2cwrite,
646 c2pread, c2pwrite,
647 errread, errwrite)
648
Thomas Wouterscf297e42007-02-23 15:07:44 +0000649 if mswindows:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000650 if p2cwrite is not None:
651 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
652 if c2pread is not None:
653 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
654 if errread is not None:
655 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000656
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000657 if bufsize == 0:
658 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000659 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000660 self.stdin = io.open(p2cwrite, 'wb', bufsize)
661 if self.universal_newlines:
662 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000663 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000664 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000666 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000667 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000668 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000670 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000671
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672
Guido van Rossum98297ee2007-11-06 21:34:58 +0000673 def _translate_newlines(self, data, encoding):
674 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
675 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000677
Brett Cannon19640502010-05-14 01:28:56 +0000678 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000679 if not self._child_created:
680 # We didn't get to successfully create a child process.
681 return
682 # In case the child hasn't been waited on, check if it's done.
Brett Cannon19640502010-05-14 01:28:56 +0000683 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000685 # Child is still running, keep us alive until we can wait on it.
686 _active.append(self)
687
688
Peter Astrand23109f02005-03-03 20:28:59 +0000689 def communicate(self, input=None):
690 """Interact with process: Send data to stdin. Read data from
691 stdout and stderr, until end-of-file is reached. Wait for
692 process to terminate. The optional input argument should be a
693 string to be sent to the child process, or None, if no data
694 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000695
Peter Astrand23109f02005-03-03 20:28:59 +0000696 communicate() returns a tuple (stdout, stderr)."""
697
698 # Optimization: If we are only using one pipe, or no pipe at
699 # all, using select() or threads is unnecessary.
700 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000701 stdout = None
702 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000703 if self.stdin:
704 if input:
705 self.stdin.write(input)
706 self.stdin.close()
707 elif self.stdout:
708 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000709 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000710 elif self.stderr:
711 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000712 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000713 self.wait()
714 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000715
Peter Astrand23109f02005-03-03 20:28:59 +0000716 return self._communicate(input)
717
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000719 def poll(self):
720 return self._internal_poll()
721
722
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723 if mswindows:
724 #
725 # Windows methods
726 #
727 def _get_handles(self, stdin, stdout, stderr):
Georg Brandla85ee5c2009-08-13 12:13:42 +0000728 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
730 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000731 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000733
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 p2cread, p2cwrite = None, None
735 c2pread, c2pwrite = None, None
736 errread, errwrite = None, None
737
Peter Astrandd38ddf42005-02-10 08:32:50 +0000738 if stdin is None:
Brian Curtine1491662010-04-24 16:33:18 +0000739 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000740 if p2cread is None:
Brian Curtine1491662010-04-24 16:33:18 +0000741 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000742 elif stdin == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000743 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000744 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745 p2cread = msvcrt.get_osfhandle(stdin)
746 else:
747 # Assuming file-like object
748 p2cread = msvcrt.get_osfhandle(stdin.fileno())
749 p2cread = self._make_inheritable(p2cread)
750
Peter Astrandd38ddf42005-02-10 08:32:50 +0000751 if stdout is None:
Brian Curtine1491662010-04-24 16:33:18 +0000752 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000753 if c2pwrite is None:
Brian Curtine1491662010-04-24 16:33:18 +0000754 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000755 elif stdout == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000756 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000757 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 c2pwrite = msvcrt.get_osfhandle(stdout)
759 else:
760 # Assuming file-like object
761 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
762 c2pwrite = self._make_inheritable(c2pwrite)
763
Peter Astrandd38ddf42005-02-10 08:32:50 +0000764 if stderr is None:
Brian Curtine1491662010-04-24 16:33:18 +0000765 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000766 if errwrite is None:
Brian Curtine1491662010-04-24 16:33:18 +0000767 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000768 elif stderr == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000769 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770 elif stderr == STDOUT:
771 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000772 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 errwrite = msvcrt.get_osfhandle(stderr)
774 else:
775 # Assuming file-like object
776 errwrite = msvcrt.get_osfhandle(stderr.fileno())
777 errwrite = self._make_inheritable(errwrite)
778
779 return (p2cread, p2cwrite,
780 c2pread, c2pwrite,
781 errread, errwrite)
782
783
784 def _make_inheritable(self, handle):
785 """Return a duplicate of handle, which is inheritable"""
Brian Curtine1491662010-04-24 16:33:18 +0000786 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
787 handle, _subprocess.GetCurrentProcess(), 0, 1,
788 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000789
790
791 def _find_w9xpopen(self):
792 """Find and return absolut path to w9xpopen.exe"""
Brian Curtine1491662010-04-24 16:33:18 +0000793 w9xpopen = os.path.join(
794 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000795 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000796 if not os.path.exists(w9xpopen):
797 # Eeek - file-not-found - possibly an embedding
798 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000799 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
800 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000802 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
803 "needed for Popen to work with your "
804 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 return w9xpopen
806
Tim Peterse718f612004-10-12 21:51:32 +0000807
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808 def _execute_child(self, args, executable, preexec_fn, close_fds,
809 cwd, env, universal_newlines,
810 startupinfo, creationflags, shell,
811 p2cread, p2cwrite,
812 c2pread, c2pwrite,
813 errread, errwrite):
814 """Execute program (MS Windows version)"""
815
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000816 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 args = list2cmdline(args)
818
Peter Astrandc1d65362004-11-07 14:30:34 +0000819 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000820 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000821 startupinfo = STARTUPINFO()
822 if None not in (p2cread, c2pwrite, errwrite):
Brian Curtine1491662010-04-24 16:33:18 +0000823 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000824 startupinfo.hStdInput = p2cread
825 startupinfo.hStdOutput = c2pwrite
826 startupinfo.hStdError = errwrite
827
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 if shell:
Brian Curtine1491662010-04-24 16:33:18 +0000829 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
830 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 comspec = os.environ.get("COMSPEC", "cmd.exe")
832 args = comspec + " /c " + args
Brian Curtine1491662010-04-24 16:33:18 +0000833 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000834 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 # Win9x, or using command.com on NT. We need to
836 # use the w9xpopen intermediate program. For more
837 # information, see KB Q150956
838 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
839 w9xpopen = self._find_w9xpopen()
840 args = '"%s" %s' % (w9xpopen, args)
841 # Not passing CREATE_NEW_CONSOLE has been known to
842 # cause random failures on win9x. Specifically a
843 # dialog: "Your program accessed mem currently in
844 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000845 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 # kill children.
Brian Curtine1491662010-04-24 16:33:18 +0000847 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 # Start the process
850 try:
Brian Curtine1491662010-04-24 16:33:18 +0000851 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000852 # no special security
853 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000854 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000855 creationflags,
856 env,
857 cwd,
858 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000859 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860 # Translate pywintypes.error to WindowsError, which is
861 # a subclass of OSError. FIXME: We should really
862 # translate errno using _sys_errlist (or simliar), but
863 # how can this be done from Python?
864 raise WindowsError(*e.args)
865
866 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000867 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 self._handle = hp
869 self.pid = pid
870 ht.Close()
871
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000872 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 # handles that only the child should have open. You need
874 # to make sure that no handles to the write end of the
875 # output pipe are maintained in this process or else the
876 # pipe will not close when the child process exits and the
877 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000878 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000880 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000882 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000883 errwrite.Close()
884
Tim Peterse718f612004-10-12 21:51:32 +0000885
Brett Cannon19640502010-05-14 01:28:56 +0000886 def _internal_poll(self, _deadstate=None,
Victor Stinner20f97be2010-05-14 21:57:25 +0000887 _WaitForSingleObject=_subprocess.WaitForSingleObject,
888 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
889 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 """Check if child process has terminated. Returns returncode
Brett Cannon19640502010-05-14 01:28:56 +0000891 attribute.
892
893 This method is called by __del__, so it can only refer to objects
894 in its local scope.
895
896 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000897 if self.returncode is None:
Brett Cannon19640502010-05-14 01:28:56 +0000898 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
899 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 return self.returncode
901
902
903 def wait(self):
904 """Wait for child process to terminate. Returns returncode
905 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000906 if self.returncode is None:
Brian Curtine1491662010-04-24 16:33:18 +0000907 _subprocess.WaitForSingleObject(self._handle,
908 _subprocess.INFINITE)
909 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910 return self.returncode
911
912
913 def _readerthread(self, fh, buffer):
914 buffer.append(fh.read())
915
916
Peter Astrand23109f02005-03-03 20:28:59 +0000917 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000918 stdout = None # Return
919 stderr = None # Return
920
921 if self.stdout:
922 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000923 stdout_thread = threading.Thread(target=self._readerthread,
924 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000925 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926 stdout_thread.start()
927 if self.stderr:
928 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000929 stderr_thread = threading.Thread(target=self._readerthread,
930 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000931 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 stderr_thread.start()
933
934 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000935 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000936 self.stdin.write(input)
937 self.stdin.close()
938
939 if self.stdout:
940 stdout_thread.join()
941 if self.stderr:
942 stderr_thread.join()
943
944 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000945 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000947 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 stderr = stderr[0]
949
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 self.wait()
951 return (stdout, stderr)
952
Christian Heimesa342c012008-04-20 21:01:16 +0000953 def send_signal(self, sig):
954 """Send a signal to the process
955 """
956 if sig == signal.SIGTERM:
957 self.terminate()
958 else:
959 raise ValueError("Only SIGTERM is supported on Windows")
960
961 def terminate(self):
962 """Terminates the process
963 """
Brian Curtine1491662010-04-24 16:33:18 +0000964 _subprocess.TerminateProcess(self._handle, 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000965
966 kill = terminate
967
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 else:
969 #
970 # POSIX methods
971 #
972 def _get_handles(self, stdin, stdout, stderr):
Georg Brandla85ee5c2009-08-13 12:13:42 +0000973 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
975 """
976 p2cread, p2cwrite = None, None
977 c2pread, c2pwrite = None, None
978 errread, errwrite = None, None
979
Peter Astrandd38ddf42005-02-10 08:32:50 +0000980 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000981 pass
982 elif stdin == PIPE:
983 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000984 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000985 p2cread = stdin
986 else:
987 # Assuming file-like object
988 p2cread = stdin.fileno()
989
Peter Astrandd38ddf42005-02-10 08:32:50 +0000990 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000991 pass
992 elif stdout == PIPE:
993 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000994 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 c2pwrite = stdout
996 else:
997 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000998 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000999
Peter Astrandd38ddf42005-02-10 08:32:50 +00001000 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001001 pass
1002 elif stderr == PIPE:
1003 errread, errwrite = os.pipe()
1004 elif stderr == STDOUT:
1005 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001006 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 errwrite = stderr
1008 else:
1009 # Assuming file-like object
1010 errwrite = stderr.fileno()
1011
1012 return (p2cread, p2cwrite,
1013 c2pread, c2pwrite,
1014 errread, errwrite)
1015
1016
1017 def _set_cloexec_flag(self, fd):
1018 try:
1019 cloexec_flag = fcntl.FD_CLOEXEC
1020 except AttributeError:
1021 cloexec_flag = 1
1022
1023 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1024 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1025
1026
1027 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001028 os.closerange(3, but)
1029 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001030
1031
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001032 def _execute_child(self, args, executable, preexec_fn, close_fds,
1033 cwd, env, universal_newlines,
1034 startupinfo, creationflags, shell,
1035 p2cread, p2cwrite,
1036 c2pread, c2pwrite,
1037 errread, errwrite):
1038 """Execute program (POSIX version)"""
1039
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001040 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001041 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001042 else:
1043 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044
1045 if shell:
1046 args = ["/bin/sh", "-c"] + args
Stefan Krah8db99c82010-07-19 14:39:36 +00001047 if executable:
1048 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049
Peter Astrandd38ddf42005-02-10 08:32:50 +00001050 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051 executable = args[0]
1052
1053 # For transferring possible exec failure from child to parent
1054 # The first char specifies the exception type: 0 means
1055 # OSError, 1 means some other error.
1056 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001057 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058 try:
Facundo Batista10706e22009-06-19 20:34:30 +00001059 self._set_cloexec_flag(errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060
Facundo Batista10706e22009-06-19 20:34:30 +00001061 gc_was_enabled = gc.isenabled()
1062 # Disable gc to avoid bug where gc -> file_dealloc ->
1063 # write to stderr -> hang. http://bugs.python.org/issue1336
1064 gc.disable()
1065 try:
1066 self.pid = os.fork()
1067 except:
1068 if gc_was_enabled:
1069 gc.enable()
1070 raise
1071 self._child_created = True
1072 if self.pid == 0:
1073 # Child
1074 try:
1075 # Close parent's pipe ends
1076 if p2cwrite is not None:
1077 os.close(p2cwrite)
1078 if c2pread is not None:
1079 os.close(c2pread)
1080 if errread is not None:
1081 os.close(errread)
1082 os.close(errpipe_read)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083
Facundo Batista10706e22009-06-19 20:34:30 +00001084 # Dup fds for child
1085 if p2cread is not None:
1086 os.dup2(p2cread, 0)
1087 if c2pwrite is not None:
1088 os.dup2(c2pwrite, 1)
1089 if errwrite is not None:
1090 os.dup2(errwrite, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091
Facundo Batista10706e22009-06-19 20:34:30 +00001092 # Close pipe fds. Make sure we don't close the
1093 # same fd more than once, or standard fds.
1094 if p2cread is not None and p2cread not in (0,):
1095 os.close(p2cread)
1096 if c2pwrite is not None and \
1097 c2pwrite not in (p2cread, 1):
1098 os.close(c2pwrite)
1099 if (errwrite is not None and
1100 errwrite not in (p2cread, c2pwrite, 2)):
1101 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102
Facundo Batista10706e22009-06-19 20:34:30 +00001103 # Close all other fds, if asked for
1104 if close_fds:
1105 self._close_fds(but=errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106
Facundo Batista10706e22009-06-19 20:34:30 +00001107 if cwd is not None:
1108 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109
Facundo Batista10706e22009-06-19 20:34:30 +00001110 if preexec_fn:
1111 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001112
Facundo Batista10706e22009-06-19 20:34:30 +00001113 if env is None:
1114 os.execvp(executable, args)
1115 else:
1116 os.execvpe(executable, args, env)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117
Facundo Batista10706e22009-06-19 20:34:30 +00001118 except:
1119 exc_type, exc_value, tb = sys.exc_info()
1120 # Save the traceback and attach it to the exception
1121 # object
1122 exc_lines = traceback.format_exception(exc_type,
1123 exc_value,
1124 tb)
1125 exc_value.child_traceback = ''.join(exc_lines)
1126 os.write(errpipe_write, pickle.dumps(exc_value))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001127
Facundo Batista10706e22009-06-19 20:34:30 +00001128 # This exitcode won't be reported to applications, so
1129 # it really doesn't matter what we return.
1130 os._exit(255)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001131
Facundo Batista10706e22009-06-19 20:34:30 +00001132 # Parent
1133 if gc_was_enabled:
1134 gc.enable()
1135 finally:
1136 # be sure the FD is closed no matter what
1137 os.close(errpipe_write)
1138
1139 if p2cread is not None and p2cwrite is not None:
1140 os.close(p2cread)
1141 if c2pwrite is not None and c2pread is not None:
1142 os.close(c2pwrite)
1143 if errwrite is not None and errread is not None:
1144 os.close(errwrite)
1145
1146 # Wait for exec to fail or succeed; possibly raising an
1147 # exception (limited to 1 MB)
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001148 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
Facundo Batista10706e22009-06-19 20:34:30 +00001149 finally:
1150 # be sure the FD is closed no matter what
1151 os.close(errpipe_read)
1152
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001153 if data:
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001154 _eintr_retry_call(os.waitpid, self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 child_exception = pickle.loads(data)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001156 for fd in (p2cwrite, c2pread, errread):
1157 if fd is not None:
1158 os.close(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001159 raise child_exception
1160
1161
Brett Cannon19640502010-05-14 01:28:56 +00001162 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1163 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1164 _WEXITSTATUS=os.WEXITSTATUS):
1165 # This method is called (indirectly) by __del__, so it cannot
1166 # refer to anything outside of its local scope."""
1167 if _WIFSIGNALED(sts):
1168 self.returncode = -_WTERMSIG(sts)
1169 elif _WIFEXITED(sts):
1170 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 else:
1172 # Should never happen
1173 raise RuntimeError("Unknown child exit status!")
1174
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175
Brett Cannon19640502010-05-14 01:28:56 +00001176 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
1177 _WNOHANG=os.WNOHANG, _os_error=os.error):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001178 """Check if child process has terminated. Returns returncode
Brett Cannon19640502010-05-14 01:28:56 +00001179 attribute.
1180
1181 This method is called by __del__, so it cannot reference anything
1182 outside of the local scope (nor can any methods it calls).
1183
1184 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001185 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001186 try:
Brett Cannon19640502010-05-14 01:28:56 +00001187 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001188 if pid == self.pid:
1189 self._handle_exitstatus(sts)
Brett Cannon19640502010-05-14 01:28:56 +00001190 except _os_error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001191 if _deadstate is not None:
1192 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193 return self.returncode
1194
1195
1196 def wait(self):
1197 """Wait for child process to terminate. Returns returncode
1198 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001199 if self.returncode is None:
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001200 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001201 self._handle_exitstatus(sts)
1202 return self.returncode
1203
1204
Peter Astrand23109f02005-03-03 20:28:59 +00001205 def _communicate(self, input):
Georg Brandlae83d6e2009-08-13 09:04:31 +00001206 if self.stdin:
1207 # Flush stdio buffer. This might block, if the user has
1208 # been writing to .stdin in an uncontrolled fashion.
1209 self.stdin.flush()
1210 if not input:
1211 self.stdin.close()
1212
1213 if _has_poll:
1214 stdout, stderr = self._communicate_with_poll(input)
1215 else:
1216 stdout, stderr = self._communicate_with_select(input)
1217
1218 # All data exchanged. Translate lists into strings.
1219 if stdout is not None:
1220 stdout = b''.join(stdout)
1221 if stderr is not None:
1222 stderr = b''.join(stderr)
1223
1224 # Translate newlines, if requested.
1225 # This also turns bytes into strings.
1226 if self.universal_newlines:
1227 if stdout is not None:
1228 stdout = self._translate_newlines(stdout,
1229 self.stdout.encoding)
1230 if stderr is not None:
1231 stderr = self._translate_newlines(stderr,
1232 self.stderr.encoding)
1233
1234 self.wait()
1235 return (stdout, stderr)
1236
1237
1238 def _communicate_with_poll(self, input):
1239 stdout = None # Return
1240 stderr = None # Return
1241 fd2file = {}
1242 fd2output = {}
1243
1244 poller = select.poll()
1245 def register_and_append(file_obj, eventmask):
1246 poller.register(file_obj.fileno(), eventmask)
1247 fd2file[file_obj.fileno()] = file_obj
1248
1249 def close_unregister_and_remove(fd):
1250 poller.unregister(fd)
1251 fd2file[fd].close()
1252 fd2file.pop(fd)
1253
1254 if self.stdin and input:
1255 register_and_append(self.stdin, select.POLLOUT)
1256
1257 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1258 if self.stdout:
1259 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1260 fd2output[self.stdout.fileno()] = stdout = []
1261 if self.stderr:
1262 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1263 fd2output[self.stderr.fileno()] = stderr = []
1264
1265 input_offset = 0
1266 while fd2file:
1267 try:
1268 ready = poller.poll()
1269 except select.error as e:
1270 if e.args[0] == errno.EINTR:
1271 continue
1272 raise
1273
1274 # XXX Rewrite these to use non-blocking I/O on the
1275 # file objects; they are no longer using C stdio!
1276
1277 for fd, mode in ready:
1278 if mode & select.POLLOUT:
1279 chunk = input[input_offset : input_offset + _PIPE_BUF]
1280 input_offset += os.write(fd, chunk)
1281 if input_offset >= len(input):
1282 close_unregister_and_remove(fd)
1283 elif mode & select_POLLIN_POLLPRI:
1284 data = os.read(fd, 4096)
1285 if not data:
1286 close_unregister_and_remove(fd)
1287 fd2output[fd].append(data)
1288 else:
1289 # Ignore hang up or errors.
1290 close_unregister_and_remove(fd)
1291
1292 return (stdout, stderr)
1293
1294
1295 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001296 read_set = []
1297 write_set = []
1298 stdout = None # Return
1299 stderr = None # Return
1300
Georg Brandlae83d6e2009-08-13 09:04:31 +00001301 if self.stdin and input:
1302 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001303 if self.stdout:
1304 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001305 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001306 if self.stderr:
1307 read_set.append(self.stderr)
1308 stderr = []
1309
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001310 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001311 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001312 try:
1313 rlist, wlist, xlist = select.select(read_set, write_set, [])
1314 except select.error as e:
1315 if e.args[0] == errno.EINTR:
1316 continue
1317 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001318
Guido van Rossum98297ee2007-11-06 21:34:58 +00001319 # XXX Rewrite these to use non-blocking I/O on the
1320 # file objects; they are no longer using C stdio!
1321
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001322 if self.stdin in wlist:
Georg Brandlae83d6e2009-08-13 09:04:31 +00001323 chunk = input[input_offset : input_offset + _PIPE_BUF]
Guido van Rossumbae07c92007-10-08 02:46:15 +00001324 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001325 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001326 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001327 self.stdin.close()
1328 write_set.remove(self.stdin)
1329
1330 if self.stdout in rlist:
1331 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001332 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001333 self.stdout.close()
1334 read_set.remove(self.stdout)
1335 stdout.append(data)
1336
1337 if self.stderr in rlist:
1338 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001339 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001340 self.stderr.close()
1341 read_set.remove(self.stderr)
1342 stderr.append(data)
1343
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001344 return (stdout, stderr)
1345
Georg Brandlae83d6e2009-08-13 09:04:31 +00001346
Christian Heimesa342c012008-04-20 21:01:16 +00001347 def send_signal(self, sig):
1348 """Send a signal to the process
1349 """
1350 os.kill(self.pid, sig)
1351
1352 def terminate(self):
1353 """Terminate the process with SIGTERM
1354 """
1355 self.send_signal(signal.SIGTERM)
1356
1357 def kill(self):
1358 """Kill the process with SIGKILL
1359 """
1360 self.send_signal(signal.SIGKILL)
1361
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001362
1363def _demo_posix():
1364 #
1365 # Example 1: Simple redirection: Get process list
1366 #
1367 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001368 print("Process list:")
1369 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001370
1371 #
1372 # Example 2: Change uid before executing child
1373 #
1374 if os.getuid() == 0:
1375 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1376 p.wait()
1377
1378 #
1379 # Example 3: Connecting several subprocesses
1380 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001381 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001382 p1 = Popen(["dmesg"], stdout=PIPE)
1383 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001384 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001385
1386 #
1387 # Example 4: Catch execution error
1388 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001389 print()
1390 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001391 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001392 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001393 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001394 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001395 print("The file didn't exist. I thought so...")
1396 print("Child traceback:")
1397 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001398 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001399 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001400 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001401 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001402
1403
1404def _demo_windows():
1405 #
1406 # Example 1: Connecting several subprocesses
1407 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001408 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001409 p1 = Popen("set", stdout=PIPE, shell=True)
1410 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001411 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001412
1413 #
1414 # Example 2: Simple execution of program
1415 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001416 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001417 p = Popen("calc")
1418 p.wait()
1419
1420
1421if __name__ == "__main__":
1422 if mswindows:
1423 _demo_windows()
1424 else:
1425 _demo_posix()