blob: ba4fac09a26b3dc2833052fcde521b2ccc95a951 [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
Brett Cannona23810f2008-05-26 19:04:21 +0000107This module also defines four 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
154
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155Exceptions
156----------
157Exceptions raised in the child process, before the new program has
158started to execute, will be re-raised in the parent. Additionally,
159the exception object will have one extra attribute called
160'child_traceback', which is a string containing traceback information
161from the childs point of view.
162
163The most common exception raised is OSError. This occurs, for
164example, when trying to execute a non-existent file. Applications
165should prepare for OSErrors.
166
167A ValueError will be raised if Popen is called with invalid arguments.
168
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000169check_call() will raise CalledProcessError, if the called process
170returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000171
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000172
173Security
174--------
175Unlike some other popen functions, this implementation will never call
176/bin/sh implicitly. This means that all characters, including shell
177metacharacters, can safely be passed to child processes.
178
179
180Popen objects
181=============
182Instances of the Popen class have the following methods:
183
184poll()
185 Check if child process has terminated. Returns returncode
186 attribute.
187
188wait()
189 Wait for child process to terminate. Returns returncode attribute.
190
191communicate(input=None)
192 Interact with process: Send data to stdin. Read data from stdout
193 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000194 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 sent to the child process, or None, if no data should be sent to
196 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000197
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 communicate() returns a tuple (stdout, stderr).
199
200 Note: The data read is buffered in memory, so do not use this
201 method if the data size is large or unlimited.
202
203The following attributes are also available:
204
205stdin
206 If the stdin argument is PIPE, this attribute is a file object
207 that provides input to the child process. Otherwise, it is None.
208
209stdout
210 If the stdout argument is PIPE, this attribute is a file object
211 that provides output from the child process. Otherwise, it is
212 None.
213
214stderr
215 If the stderr argument is PIPE, this attribute is file object that
216 provides error output from the child process. Otherwise, it is
217 None.
218
219pid
220 The process ID of the child process.
221
222returncode
223 The child return code. A None value indicates that the process
224 hasn't terminated yet. A negative value -N indicates that the
225 child was terminated by signal N (UNIX only).
226
227
228Replacing older functions with the subprocess module
229====================================================
230In this section, "a ==> b" means that b can be used as a replacement
231for a.
232
233Note: All functions in this section fail (more or less) silently if
234the executed program cannot be found; this module raises an OSError
235exception.
236
237In the following examples, we assume that the subprocess module is
238imported with "from subprocess import *".
239
240
241Replacing /bin/sh shell backquote
242---------------------------------
243output=`mycmd myarg`
244==>
245output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
246
247
248Replacing shell pipe line
249-------------------------
250output=`dmesg | grep hda`
251==>
252p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000253p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254output = p2.communicate()[0]
255
256
257Replacing os.system()
258---------------------
259sts = os.system("mycmd" + " myarg")
260==>
261p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000262pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264Note:
265
266* Calling the program through the shell is usually not required.
267
268* It's easier to look at the returncode attribute than the
269 exitstatus.
270
271A more real-world example would look like this:
272
273try:
274 retcode = call("mycmd" + " myarg", shell=True)
275 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000276 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000278 print("Child returned", retcode, file=sys.stderr)
279except OSError as e:
280 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282
283Replacing os.spawn*
284-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000285P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286
287pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
288==>
289pid = Popen(["/bin/mycmd", "myarg"]).pid
290
291
292P_WAIT example:
293
294retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
295==>
296retcode = call(["/bin/mycmd", "myarg"])
297
298
Tim Peterse718f612004-10-12 21:51:32 +0000299Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300
301os.spawnvp(os.P_NOWAIT, path, args)
302==>
303Popen([path] + args[1:])
304
305
Tim Peterse718f612004-10-12 21:51:32 +0000306Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307
308os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
309==>
310Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311"""
312
313import sys
314mswindows = (sys.platform == "win32")
315
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000316import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000319import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000320import signal
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321
Peter Astrand454f7672005-01-01 09:36:35 +0000322# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000323class CalledProcessError(Exception):
Peter Astrand454f7672005-01-01 09:36:35 +0000324 """This exception is raised when a process run by check_call() returns
325 a non-zero exit status. The exit status will be stored in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000326 returncode attribute."""
327 def __init__(self, returncode, cmd):
328 self.returncode = returncode
329 self.cmd = cmd
330 def __str__(self):
331 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
332
Peter Astrand454f7672005-01-01 09:36:35 +0000333
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334if mswindows:
335 import threading
336 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000337 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000339 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
340 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
341 from win32api import GetCurrentProcess, DuplicateHandle, \
342 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000343 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000345 from win32process import CreateProcess, STARTUPINFO, \
346 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000347 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Christian Heimesa342c012008-04-20 21:01:16 +0000348 from win32process import TerminateProcess
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000350 else:
351 from _subprocess import *
352 class STARTUPINFO:
353 dwFlags = 0
354 hStdInput = None
355 hStdOutput = None
356 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000357 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000358 class pywintypes:
359 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360else:
361 import select
362 import errno
363 import fcntl
364 import pickle
365
Brett Cannona23810f2008-05-26 19:04:21 +0000366__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
367 "getoutput", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368
369try:
370 MAXFD = os.sysconf("SC_OPEN_MAX")
371except:
372 MAXFD = 256
373
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374_active = []
375
376def _cleanup():
377 for inst in _active[:]:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000378 res = inst.poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000379 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000380 try:
381 _active.remove(inst)
382 except ValueError:
383 # This can happen if two threads create a new Popen instance.
384 # It's harmless that it was already removed, so ignore.
385 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386
387PIPE = -1
388STDOUT = -2
389
390
Peter Astrand5f5e1412004-12-05 20:15:36 +0000391def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 """Run command with arguments. Wait for command to complete, then
393 return the returncode attribute.
394
395 The arguments are the same as for the Popen constructor. Example:
396
397 retcode = call(["ls", "-l"])
398 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000399 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400
401
Peter Astrand454f7672005-01-01 09:36:35 +0000402def check_call(*popenargs, **kwargs):
403 """Run command with arguments. Wait for command to complete. If
404 the exit code was zero then return, otherwise raise
405 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000406 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000407
408 The arguments are the same as for the Popen constructor. Example:
409
410 check_call(["ls", "-l"])
411 """
412 retcode = call(*popenargs, **kwargs)
413 cmd = kwargs.get("args")
414 if cmd is None:
415 cmd = popenargs[0]
416 if retcode:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 raise CalledProcessError(retcode, cmd)
Peter Astrand454f7672005-01-01 09:36:35 +0000418 return retcode
419
420
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421def list2cmdline(seq):
422 """
423 Translate a sequence of arguments into a command line
424 string, using the same rules as the MS C runtime:
425
426 1) Arguments are delimited by white space, which is either a
427 space or a tab.
428
429 2) A string surrounded by double quotation marks is
430 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000431 or pipe characters contained within. A quoted string can be
432 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433
434 3) A double quotation mark preceded by a backslash is
435 interpreted as a literal double quotation mark.
436
437 4) Backslashes are interpreted literally, unless they
438 immediately precede a double quotation mark.
439
440 5) If backslashes immediately precede a double quotation mark,
441 every pair of backslashes is interpreted as a literal
442 backslash. If the number of backslashes is odd, the last
443 backslash escapes the next double quotation mark as
444 described in rule 3.
445 """
446
447 # See
448 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
449 result = []
450 needquote = False
451 for arg in seq:
452 bs_buf = []
453
454 # Add a space to separate this argument from the others
455 if result:
456 result.append(' ')
457
Christian Heimesfdab48e2008-01-20 09:06:41 +0000458 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 if needquote:
460 result.append('"')
461
462 for c in arg:
463 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000464 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 bs_buf.append(c)
466 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000467 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 result.append('\\' * len(bs_buf)*2)
469 bs_buf = []
470 result.append('\\"')
471 else:
472 # Normal char
473 if bs_buf:
474 result.extend(bs_buf)
475 bs_buf = []
476 result.append(c)
477
Christian Heimesfdab48e2008-01-20 09:06:41 +0000478 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 if bs_buf:
480 result.extend(bs_buf)
481
482 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000483 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 result.append('"')
485
486 return ''.join(result)
487
488
Brett Cannona23810f2008-05-26 19:04:21 +0000489# Various tools for executing commands and looking at their output and status.
490#
491# NB This only works (and is only relevant) for UNIX.
492
493def getstatusoutput(cmd):
494 """Return (status, output) of executing cmd in a shell.
495
496 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
497 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
498 returned output will contain output or error messages. A trailing newline
499 is stripped from the output. The exit status for the command can be
500 interpreted according to the rules for the C function wait(). Example:
501
502 >>> import subprocess
503 >>> subprocess.getstatusoutput('ls /bin/ls')
504 (0, '/bin/ls')
505 >>> subprocess.getstatusoutput('cat /bin/junk')
506 (256, 'cat: /bin/junk: No such file or directory')
507 >>> subprocess.getstatusoutput('/bin/junk')
508 (256, 'sh: /bin/junk: not found')
509 """
510 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
511 text = pipe.read()
512 sts = pipe.close()
513 if sts is None: sts = 0
514 if text[-1:] == '\n': text = text[:-1]
515 return sts, text
516
517
518def getoutput(cmd):
519 """Return output (stdout or stderr) of executing cmd in a shell.
520
521 Like getstatusoutput(), except the exit status is ignored and the return
522 value is a string containing the command's output. Example:
523
524 >>> import subprocess
525 >>> subprocess.getoutput('ls /bin/ls')
526 '/bin/ls'
527 """
528 return getstatusoutput(cmd)[1]
529
530
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531class Popen(object):
532 def __init__(self, args, bufsize=0, executable=None,
533 stdin=None, stdout=None, stderr=None,
534 preexec_fn=None, close_fds=False, shell=False,
535 cwd=None, env=None, universal_newlines=False,
536 startupinfo=None, creationflags=0):
537 """Create new Popen instance."""
538 _cleanup()
539
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000541 if bufsize is None:
542 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000543 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000544 raise TypeError("bufsize must be an integer")
545
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000547 if preexec_fn is not None:
548 raise ValueError("preexec_fn is not supported on Windows "
549 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000550 if close_fds and (stdin is not None or stdout is not None or
551 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000552 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000553 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 else:
555 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000556 if startupinfo is not None:
557 raise ValueError("startupinfo is only supported on Windows "
558 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000560 raise ValueError("creationflags is only supported on Windows "
561 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562
Tim Peterse718f612004-10-12 21:51:32 +0000563 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 self.stdout = None
565 self.stderr = None
566 self.pid = None
567 self.returncode = None
568 self.universal_newlines = universal_newlines
569
570 # Input and output objects. The general principle is like
571 # this:
572 #
573 # Parent Child
574 # ------ -----
575 # p2cwrite ---stdin---> p2cread
576 # c2pread <--stdout--- c2pwrite
577 # errread <--stderr--- errwrite
578 #
579 # On POSIX, the child objects are file descriptors. On
580 # Windows, these are Windows file handles. The parent objects
581 # are file descriptors on both platforms. The parent objects
582 # are None when not using PIPEs. The child objects are None
583 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 (p2cread, p2cwrite,
586 c2pread, c2pwrite,
587 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
588
589 self._execute_child(args, executable, preexec_fn, close_fds,
590 cwd, env, universal_newlines,
591 startupinfo, creationflags, shell,
592 p2cread, p2cwrite,
593 c2pread, c2pwrite,
594 errread, errwrite)
595
Thomas Wouterscf297e42007-02-23 15:07:44 +0000596 # On Windows, you cannot just redirect one or two handles: You
597 # either have to redirect all three or none. If the subprocess
598 # user has only redirected one or two handles, we are
599 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000601 if mswindows:
602 if stdin is None and p2cwrite is not None:
603 os.close(p2cwrite)
604 p2cwrite = None
605 if stdout is None and c2pread is not None:
606 os.close(c2pread)
607 c2pread = None
608 if stderr is None and errread is not None:
609 os.close(errread)
610 errread = None
611
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000612 if bufsize == 0:
613 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000614 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000615 self.stdin = io.open(p2cwrite, 'wb', bufsize)
616 if self.universal_newlines:
617 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000618 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000619 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000621 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000622 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000623 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000625 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627
Guido van Rossum98297ee2007-11-06 21:34:58 +0000628 def _translate_newlines(self, data, encoding):
629 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
630 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000632
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634 if not self._child_created:
635 # We didn't get to successfully create a child process.
636 return
637 # In case the child hasn't been waited on, check if it's done.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000638 self.poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 # Child is still running, keep us alive until we can wait on it.
641 _active.append(self)
642
643
Peter Astrand23109f02005-03-03 20:28:59 +0000644 def communicate(self, input=None):
645 """Interact with process: Send data to stdin. Read data from
646 stdout and stderr, until end-of-file is reached. Wait for
647 process to terminate. The optional input argument should be a
648 string to be sent to the child process, or None, if no data
649 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000650
Peter Astrand23109f02005-03-03 20:28:59 +0000651 communicate() returns a tuple (stdout, stderr)."""
652
653 # Optimization: If we are only using one pipe, or no pipe at
654 # all, using select() or threads is unnecessary.
655 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000656 stdout = None
657 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000658 if self.stdin:
659 if input:
660 self.stdin.write(input)
661 self.stdin.close()
662 elif self.stdout:
663 stdout = self.stdout.read()
664 elif self.stderr:
665 stderr = self.stderr.read()
666 self.wait()
667 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000668
Peter Astrand23109f02005-03-03 20:28:59 +0000669 return self._communicate(input)
670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671
672 if mswindows:
673 #
674 # Windows methods
675 #
676 def _get_handles(self, stdin, stdout, stderr):
677 """Construct and return tupel with IO objects:
678 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
679 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000680 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000682
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000683 p2cread, p2cwrite = None, None
684 c2pread, c2pwrite = None, None
685 errread, errwrite = None, None
686
Peter Astrandd38ddf42005-02-10 08:32:50 +0000687 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000688 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000689 if p2cread is not None:
690 pass
691 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000692 p2cread, p2cwrite = CreatePipe(None, 0)
693 # Detach and turn into fd
694 p2cwrite = p2cwrite.Detach()
695 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000696 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697 p2cread = msvcrt.get_osfhandle(stdin)
698 else:
699 # Assuming file-like object
700 p2cread = msvcrt.get_osfhandle(stdin.fileno())
701 p2cread = self._make_inheritable(p2cread)
702
Peter Astrandd38ddf42005-02-10 08:32:50 +0000703 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000705 if c2pwrite is not None:
706 pass
707 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000708 c2pread, c2pwrite = CreatePipe(None, 0)
709 # Detach and turn into fd
710 c2pread = c2pread.Detach()
711 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000712 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 c2pwrite = msvcrt.get_osfhandle(stdout)
714 else:
715 # Assuming file-like object
716 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
717 c2pwrite = self._make_inheritable(c2pwrite)
718
Peter Astrandd38ddf42005-02-10 08:32:50 +0000719 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000721 if errwrite is not None:
722 pass
723 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724 errread, errwrite = CreatePipe(None, 0)
725 # Detach and turn into fd
726 errread = errread.Detach()
727 errread = msvcrt.open_osfhandle(errread, 0)
728 elif stderr == STDOUT:
729 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000730 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 errwrite = msvcrt.get_osfhandle(stderr)
732 else:
733 # Assuming file-like object
734 errwrite = msvcrt.get_osfhandle(stderr.fileno())
735 errwrite = self._make_inheritable(errwrite)
736
737 return (p2cread, p2cwrite,
738 c2pread, c2pwrite,
739 errread, errwrite)
740
741
742 def _make_inheritable(self, handle):
743 """Return a duplicate of handle, which is inheritable"""
744 return DuplicateHandle(GetCurrentProcess(), handle,
745 GetCurrentProcess(), 0, 1,
746 DUPLICATE_SAME_ACCESS)
747
748
749 def _find_w9xpopen(self):
750 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000751 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
752 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 if not os.path.exists(w9xpopen):
754 # Eeek - file-not-found - possibly an embedding
755 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000756 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
757 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000759 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
760 "needed for Popen to work with your "
761 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 return w9xpopen
763
Tim Peterse718f612004-10-12 21:51:32 +0000764
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 def _execute_child(self, args, executable, preexec_fn, close_fds,
766 cwd, env, universal_newlines,
767 startupinfo, creationflags, shell,
768 p2cread, p2cwrite,
769 c2pread, c2pwrite,
770 errread, errwrite):
771 """Execute program (MS Windows version)"""
772
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000773 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774 args = list2cmdline(args)
775
Peter Astrandc1d65362004-11-07 14:30:34 +0000776 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000777 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000778 startupinfo = STARTUPINFO()
779 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000780 startupinfo.dwFlags |= STARTF_USESTDHANDLES
781 startupinfo.hStdInput = p2cread
782 startupinfo.hStdOutput = c2pwrite
783 startupinfo.hStdError = errwrite
784
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000786 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
787 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000788 comspec = os.environ.get("COMSPEC", "cmd.exe")
789 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000790 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000791 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 # Win9x, or using command.com on NT. We need to
793 # use the w9xpopen intermediate program. For more
794 # information, see KB Q150956
795 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
796 w9xpopen = self._find_w9xpopen()
797 args = '"%s" %s' % (w9xpopen, args)
798 # Not passing CREATE_NEW_CONSOLE has been known to
799 # cause random failures on win9x. Specifically a
800 # dialog: "Your program accessed mem currently in
801 # use at xxx" and a hopeful warning about the
802 # stability of your system. Cost is Ctrl+C wont
803 # kill children.
804 creationflags |= CREATE_NEW_CONSOLE
805
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000806 # Start the process
807 try:
808 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000809 # no special security
810 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000811 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000812 creationflags,
813 env,
814 cwd,
815 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000816 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 # Translate pywintypes.error to WindowsError, which is
818 # a subclass of OSError. FIXME: We should really
819 # translate errno using _sys_errlist (or simliar), but
820 # how can this be done from Python?
821 raise WindowsError(*e.args)
822
823 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 self._handle = hp
826 self.pid = pid
827 ht.Close()
828
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000829 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 # handles that only the child should have open. You need
831 # to make sure that no handles to the write end of the
832 # output pipe are maintained in this process or else the
833 # pipe will not close when the child process exits and the
834 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000835 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000837 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000839 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 errwrite.Close()
841
Tim Peterse718f612004-10-12 21:51:32 +0000842
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 """Check if child process has terminated. Returns returncode
845 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000846 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
848 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 return self.returncode
850
851
852 def wait(self):
853 """Wait for child process to terminate. Returns returncode
854 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000855 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856 obj = WaitForSingleObject(self._handle, INFINITE)
857 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 return self.returncode
859
860
861 def _readerthread(self, fh, buffer):
862 buffer.append(fh.read())
863
864
Peter Astrand23109f02005-03-03 20:28:59 +0000865 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 stdout = None # Return
867 stderr = None # Return
868
869 if self.stdout:
870 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000871 stdout_thread = threading.Thread(target=self._readerthread,
872 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 stdout_thread.setDaemon(True)
874 stdout_thread.start()
875 if self.stderr:
876 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000877 stderr_thread = threading.Thread(target=self._readerthread,
878 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 stderr_thread.setDaemon(True)
880 stderr_thread.start()
881
882 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000883 if input is not None:
Guido van Rossumc12a8132007-10-26 04:29:23 +0000884 if isinstance(input, str):
885 input = input.encode()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886 self.stdin.write(input)
887 self.stdin.close()
888
889 if self.stdout:
890 stdout_thread.join()
891 if self.stderr:
892 stderr_thread.join()
893
894 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000895 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000896 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000897 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898 stderr = stderr[0]
899
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 self.wait()
901 return (stdout, stderr)
902
Christian Heimesa342c012008-04-20 21:01:16 +0000903 def send_signal(self, sig):
904 """Send a signal to the process
905 """
906 if sig == signal.SIGTERM:
907 self.terminate()
908 else:
909 raise ValueError("Only SIGTERM is supported on Windows")
910
911 def terminate(self):
912 """Terminates the process
913 """
914 TerminateProcess(self._handle, 1)
915
916 kill = terminate
917
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000918 else:
919 #
920 # POSIX methods
921 #
922 def _get_handles(self, stdin, stdout, stderr):
923 """Construct and return tupel with IO objects:
924 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
925 """
926 p2cread, p2cwrite = None, None
927 c2pread, c2pwrite = None, None
928 errread, errwrite = None, None
929
Peter Astrandd38ddf42005-02-10 08:32:50 +0000930 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 pass
932 elif stdin == PIPE:
933 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000934 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 p2cread = stdin
936 else:
937 # Assuming file-like object
938 p2cread = stdin.fileno()
939
Peter Astrandd38ddf42005-02-10 08:32:50 +0000940 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000941 pass
942 elif stdout == PIPE:
943 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000944 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 c2pwrite = stdout
946 else:
947 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000948 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949
Peter Astrandd38ddf42005-02-10 08:32:50 +0000950 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 pass
952 elif stderr == PIPE:
953 errread, errwrite = os.pipe()
954 elif stderr == STDOUT:
955 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000956 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 errwrite = stderr
958 else:
959 # Assuming file-like object
960 errwrite = stderr.fileno()
961
962 return (p2cread, p2cwrite,
963 c2pread, c2pwrite,
964 errread, errwrite)
965
966
967 def _set_cloexec_flag(self, fd):
968 try:
969 cloexec_flag = fcntl.FD_CLOEXEC
970 except AttributeError:
971 cloexec_flag = 1
972
973 old = fcntl.fcntl(fd, fcntl.F_GETFD)
974 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
975
976
977 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000978 os.closerange(3, but)
979 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +0000980
981
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 def _execute_child(self, args, executable, preexec_fn, close_fds,
983 cwd, env, universal_newlines,
984 startupinfo, creationflags, shell,
985 p2cread, p2cwrite,
986 c2pread, c2pwrite,
987 errread, errwrite):
988 """Execute program (POSIX version)"""
989
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000990 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000991 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000992 else:
993 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000994
995 if shell:
996 args = ["/bin/sh", "-c"] + args
997
Peter Astrandd38ddf42005-02-10 08:32:50 +0000998 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000999 executable = args[0]
1000
1001 # For transferring possible exec failure from child to parent
1002 # The first char specifies the exception type: 0 means
1003 # OSError, 1 means some other error.
1004 errpipe_read, errpipe_write = os.pipe()
1005 self._set_cloexec_flag(errpipe_write)
1006
Christian Heimesfdab48e2008-01-20 09:06:41 +00001007 gc_was_enabled = gc.isenabled()
1008 # Disable gc to avoid bug where gc -> file_dealloc ->
1009 # write to stderr -> hang. http://bugs.python.org/issue1336
1010 gc.disable()
1011 try:
1012 self.pid = os.fork()
1013 except:
1014 if gc_was_enabled:
1015 gc.enable()
1016 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001017 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 if self.pid == 0:
1019 # Child
1020 try:
1021 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +00001022 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001023 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001024 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001025 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001026 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 os.close(errread)
1028 os.close(errpipe_read)
1029
1030 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +00001031 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001032 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001033 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001035 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 os.dup2(errwrite, 2)
1037
Thomas Wouters89f507f2006-12-13 04:49:30 +00001038 # Close pipe fds. Make sure we don't close the same
1039 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +00001040 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001041 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001042 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001043 os.close(c2pwrite)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001044 if (errwrite is not None and
1045 errwrite not in (p2cread, c2pwrite, 2)):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001046 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047
1048 # Close all other fds, if asked for
1049 if close_fds:
1050 self._close_fds(but=errpipe_write)
1051
Peter Astrandd38ddf42005-02-10 08:32:50 +00001052 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053 os.chdir(cwd)
1054
1055 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +00001056 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057
Peter Astrandd38ddf42005-02-10 08:32:50 +00001058 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059 os.execvp(executable, args)
1060 else:
1061 os.execvpe(executable, args, env)
1062
1063 except:
1064 exc_type, exc_value, tb = sys.exc_info()
1065 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001066 exc_lines = traceback.format_exception(exc_type,
1067 exc_value,
1068 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 exc_value.child_traceback = ''.join(exc_lines)
1070 os.write(errpipe_write, pickle.dumps(exc_value))
1071
1072 # This exitcode won't be reported to applications, so it
1073 # really doesn't matter what we return.
1074 os._exit(255)
1075
1076 # Parent
Christian Heimesfdab48e2008-01-20 09:06:41 +00001077 if gc_was_enabled:
1078 gc.enable()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001079 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001080 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001082 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001084 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 os.close(errwrite)
1086
1087 # Wait for exec to fail or succeed; possibly raising exception
1088 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1089 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001090 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001091 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092 child_exception = pickle.loads(data)
1093 raise child_exception
1094
1095
1096 def _handle_exitstatus(self, sts):
1097 if os.WIFSIGNALED(sts):
1098 self.returncode = -os.WTERMSIG(sts)
1099 elif os.WIFEXITED(sts):
1100 self.returncode = os.WEXITSTATUS(sts)
1101 else:
1102 # Should never happen
1103 raise RuntimeError("Unknown child exit status!")
1104
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001106 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001107 """Check if child process has terminated. Returns returncode
1108 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001109 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110 try:
1111 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1112 if pid == self.pid:
1113 self._handle_exitstatus(sts)
1114 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001115 if _deadstate is not None:
1116 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117 return self.returncode
1118
1119
1120 def wait(self):
1121 """Wait for child process to terminate. Returns returncode
1122 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001123 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001124 pid, sts = os.waitpid(self.pid, 0)
1125 self._handle_exitstatus(sts)
1126 return self.returncode
1127
1128
Peter Astrand23109f02005-03-03 20:28:59 +00001129 def _communicate(self, input):
Guido van Rossumbae07c92007-10-08 02:46:15 +00001130 if self.stdin:
1131 if isinstance(input, str): # Unicode
1132 input = input.encode("utf-8") # XXX What else?
Guido van Rossum98297ee2007-11-06 21:34:58 +00001133 input = bytes(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 read_set = []
1135 write_set = []
1136 stdout = None # Return
1137 stderr = None # Return
1138
1139 if self.stdin:
1140 # Flush stdio buffer. This might block, if the user has
1141 # been writing to .stdin in an uncontrolled fashion.
1142 self.stdin.flush()
1143 if input:
1144 write_set.append(self.stdin)
1145 else:
1146 self.stdin.close()
1147 if self.stdout:
1148 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001149 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001150 if self.stderr:
1151 read_set.append(self.stderr)
1152 stderr = []
1153
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001154 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 while read_set or write_set:
1156 rlist, wlist, xlist = select.select(read_set, write_set, [])
1157
Guido van Rossum98297ee2007-11-06 21:34:58 +00001158 # XXX Rewrite these to use non-blocking I/O on the
1159 # file objects; they are no longer using C stdio!
1160
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161 if self.stdin in wlist:
1162 # When select has indicated that the file is writable,
1163 # we can write up to PIPE_BUF bytes without risk
1164 # blocking. POSIX defines PIPE_BUF >= 512
Guido van Rossumbae07c92007-10-08 02:46:15 +00001165 chunk = input[input_offset : input_offset + 512]
1166 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001167 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001168 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001169 self.stdin.close()
1170 write_set.remove(self.stdin)
1171
1172 if self.stdout in rlist:
1173 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001174 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175 self.stdout.close()
1176 read_set.remove(self.stdout)
1177 stdout.append(data)
1178
1179 if self.stderr in rlist:
1180 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001181 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001182 self.stderr.close()
1183 read_set.remove(self.stderr)
1184 stderr.append(data)
1185
1186 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001187 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001188 stdout = b"".join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001189 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001190 stderr = b"".join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001191
Guido van Rossum98297ee2007-11-06 21:34:58 +00001192 # Translate newlines, if requested.
1193 # This also turns bytes into strings.
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001194 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001195 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001196 stdout = self._translate_newlines(stdout,
1197 self.stdout.encoding)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001198 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001199 stderr = self._translate_newlines(stderr,
1200 self.stderr.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001201
1202 self.wait()
1203 return (stdout, stderr)
1204
Christian Heimesa342c012008-04-20 21:01:16 +00001205 def send_signal(self, sig):
1206 """Send a signal to the process
1207 """
1208 os.kill(self.pid, sig)
1209
1210 def terminate(self):
1211 """Terminate the process with SIGTERM
1212 """
1213 self.send_signal(signal.SIGTERM)
1214
1215 def kill(self):
1216 """Kill the process with SIGKILL
1217 """
1218 self.send_signal(signal.SIGKILL)
1219
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001220
1221def _demo_posix():
1222 #
1223 # Example 1: Simple redirection: Get process list
1224 #
1225 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001226 print("Process list:")
1227 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001228
1229 #
1230 # Example 2: Change uid before executing child
1231 #
1232 if os.getuid() == 0:
1233 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1234 p.wait()
1235
1236 #
1237 # Example 3: Connecting several subprocesses
1238 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001239 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001240 p1 = Popen(["dmesg"], stdout=PIPE)
1241 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001242 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001243
1244 #
1245 # Example 4: Catch execution error
1246 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001247 print()
1248 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001249 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001250 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001251 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001252 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001253 print("The file didn't exist. I thought so...")
1254 print("Child traceback:")
1255 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001256 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001257 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001258 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001259 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001260
1261
1262def _demo_windows():
1263 #
1264 # Example 1: Connecting several subprocesses
1265 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001266 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001267 p1 = Popen("set", stdout=PIPE, shell=True)
1268 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001269 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001270
1271 #
1272 # Example 2: Simple execution of program
1273 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001274 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001275 p = Popen("calc")
1276 p.wait()
1277
1278
1279if __name__ == "__main__":
1280 if mswindows:
1281 _demo_windows()
1282 else:
1283 _demo_posix()