blob: d46aa552a8ac313d1d41fc13d874a7d5995ecadc [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 +000020commands.*
21
22Information about how the subprocess module can be used to replace these
23modules and functions can be found below.
24
25
26
27Using the subprocess module
28===========================
29This module defines one class called Popen:
30
31class Popen(args, bufsize=0, executable=None,
32 stdin=None, stdout=None, stderr=None,
33 preexec_fn=None, close_fds=False, shell=False,
34 cwd=None, env=None, universal_newlines=False,
35 startupinfo=None, creationflags=0):
36
37
38Arguments are:
39
40args should be a string, or a sequence of program arguments. The
41program to execute is normally the first item in the args sequence or
42string, but can be explicitly set by using the executable argument.
43
44On UNIX, with shell=False (default): In this case, the Popen class
45uses os.execvp() to execute the child program. args should normally
46be a sequence. A string will be treated as a sequence with the string
47as the only item (the program to execute).
48
49On UNIX, with shell=True: If args is a string, it specifies the
50command string to execute through the shell. If args is a sequence,
51the first item specifies the command string, and any additional items
52will be treated as additional shell arguments.
53
54On Windows: the Popen class uses CreateProcess() to execute the child
55program, which operates on strings. If args is a sequence, it will be
56converted to a string using the list2cmdline method. Please note that
57not all MS Windows applications interpret the command line the same
58way: The list2cmdline is designed for applications using the same
59rules as the MS C runtime.
60
61bufsize, if given, has the same meaning as the corresponding argument
62to the built-in open() function: 0 means unbuffered, 1 means line
63buffered, any other positive value means use a buffer of
64(approximately) that size. A negative bufsize means to use the system
65default, which usually means fully buffered. The default value for
66bufsize is 0 (unbuffered).
67
68stdin, stdout and stderr specify the executed programs' standard
69input, standard output and standard error file handles, respectively.
70Valid values are PIPE, an existing file descriptor (a positive
71integer), an existing file object, and None. PIPE indicates that a
72new pipe to the child should be created. With None, no redirection
73will occur; the child's file handles will be inherited from the
74parent. Additionally, stderr can be STDOUT, which indicates that the
75stderr data from the applications should be captured into the same
76file handle as for stdout.
77
78If preexec_fn is set to a callable object, this object will be called
79in the child process just before the child is executed.
80
81If close_fds is true, all file descriptors except 0, 1 and 2 will be
82closed before the child process is executed.
83
84if shell is true, the specified command will be executed through the
85shell.
86
87If cwd is not None, the current directory will be changed to cwd
88before the child is executed.
89
90If env is not None, it defines the environment variables for the new
91process.
92
93If universal_newlines is true, the file objects stdout and stderr are
94opened as a text files, but lines may be terminated by any of '\n',
95the Unix end-of-line convention, '\r', the Macintosh convention or
96'\r\n', the Windows convention. All of these external representations
97are seen as '\n' by the Python program. Note: This feature is only
98available if Python is built with universal newline support (the
99default). Also, the newlines attribute of the file objects stdout,
100stdin and stderr are not updated by the communicate() method.
101
102The startupinfo and creationflags, if given, will be passed to the
103underlying CreateProcess() function. They can specify things such as
104appearance of the main window and priority for the new process.
105(Windows only)
106
107
108This module also defines two shortcut functions:
109
Peter Astrand5f5e1412004-12-05 20:15:36 +0000110call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 Run command with arguments. Wait for command to complete, then
112 return the returncode attribute.
113
114 The arguments are the same as for the Popen constructor. Example:
115
116 retcode = call(["ls", "-l"])
117
Peter Astrand454f7672005-01-01 09:36:35 +0000118check_call(*popenargs, **kwargs):
119 Run command with arguments. Wait for command to complete. If the
120 exit code was zero then return, otherwise raise
121 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000122 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000123
124 The arguments are the same as for the Popen constructor. Example:
125
126 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127
128Exceptions
129----------
130Exceptions raised in the child process, before the new program has
131started to execute, will be re-raised in the parent. Additionally,
132the exception object will have one extra attribute called
133'child_traceback', which is a string containing traceback information
134from the childs point of view.
135
136The most common exception raised is OSError. This occurs, for
137example, when trying to execute a non-existent file. Applications
138should prepare for OSErrors.
139
140A ValueError will be raised if Popen is called with invalid arguments.
141
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142check_call() will raise CalledProcessError, if the called process
143returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000144
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145
146Security
147--------
148Unlike some other popen functions, this implementation will never call
149/bin/sh implicitly. This means that all characters, including shell
150metacharacters, can safely be passed to child processes.
151
152
153Popen objects
154=============
155Instances of the Popen class have the following methods:
156
157poll()
158 Check if child process has terminated. Returns returncode
159 attribute.
160
161wait()
162 Wait for child process to terminate. Returns returncode attribute.
163
164communicate(input=None)
165 Interact with process: Send data to stdin. Read data from stdout
166 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000167 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 sent to the child process, or None, if no data should be sent to
169 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000170
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 communicate() returns a tuple (stdout, stderr).
172
173 Note: The data read is buffered in memory, so do not use this
174 method if the data size is large or unlimited.
175
176The following attributes are also available:
177
178stdin
179 If the stdin argument is PIPE, this attribute is a file object
180 that provides input to the child process. Otherwise, it is None.
181
182stdout
183 If the stdout argument is PIPE, this attribute is a file object
184 that provides output from the child process. Otherwise, it is
185 None.
186
187stderr
188 If the stderr argument is PIPE, this attribute is file object that
189 provides error output from the child process. Otherwise, it is
190 None.
191
192pid
193 The process ID of the child process.
194
195returncode
196 The child return code. A None value indicates that the process
197 hasn't terminated yet. A negative value -N indicates that the
198 child was terminated by signal N (UNIX only).
199
200
201Replacing older functions with the subprocess module
202====================================================
203In this section, "a ==> b" means that b can be used as a replacement
204for a.
205
206Note: All functions in this section fail (more or less) silently if
207the executed program cannot be found; this module raises an OSError
208exception.
209
210In the following examples, we assume that the subprocess module is
211imported with "from subprocess import *".
212
213
214Replacing /bin/sh shell backquote
215---------------------------------
216output=`mycmd myarg`
217==>
218output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
219
220
221Replacing shell pipe line
222-------------------------
223output=`dmesg | grep hda`
224==>
225p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000226p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227output = p2.communicate()[0]
228
229
230Replacing os.system()
231---------------------
232sts = os.system("mycmd" + " myarg")
233==>
234p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236
237Note:
238
239* Calling the program through the shell is usually not required.
240
241* It's easier to look at the returncode attribute than the
242 exitstatus.
243
244A more real-world example would look like this:
245
246try:
247 retcode = call("mycmd" + " myarg", shell=True)
248 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000249 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000251 print("Child returned", retcode, file=sys.stderr)
252except OSError as e:
253 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254
255
256Replacing os.spawn*
257-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000258P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
261==>
262pid = Popen(["/bin/mycmd", "myarg"]).pid
263
264
265P_WAIT example:
266
267retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
268==>
269retcode = call(["/bin/mycmd", "myarg"])
270
271
Tim Peterse718f612004-10-12 21:51:32 +0000272Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273
274os.spawnvp(os.P_NOWAIT, path, args)
275==>
276Popen([path] + args[1:])
277
278
Tim Peterse718f612004-10-12 21:51:32 +0000279Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280
281os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
282==>
283Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284"""
285
286import sys
287mswindows = (sys.platform == "win32")
288
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000289import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291import traceback
292
Peter Astrand454f7672005-01-01 09:36:35 +0000293# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294class CalledProcessError(Exception):
Peter Astrand454f7672005-01-01 09:36:35 +0000295 """This exception is raised when a process run by check_call() returns
296 a non-zero exit status. The exit status will be stored in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000297 returncode attribute."""
298 def __init__(self, returncode, cmd):
299 self.returncode = returncode
300 self.cmd = cmd
301 def __str__(self):
302 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
303
Peter Astrand454f7672005-01-01 09:36:35 +0000304
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305if mswindows:
306 import threading
307 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000308 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000310 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
311 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
312 from win32api import GetCurrentProcess, DuplicateHandle, \
313 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000314 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000316 from win32process import CreateProcess, STARTUPINFO, \
317 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000318 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000320 else:
321 from _subprocess import *
322 class STARTUPINFO:
323 dwFlags = 0
324 hStdInput = None
325 hStdOutput = None
326 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000327 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000328 class pywintypes:
329 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330else:
331 import select
332 import errno
333 import fcntl
334 import pickle
335
Peter Astrand454f7672005-01-01 09:36:35 +0000336__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337
338try:
339 MAXFD = os.sysconf("SC_OPEN_MAX")
340except:
341 MAXFD = 256
342
343# True/False does not exist on 2.2.0
344try:
345 False
346except NameError:
347 False = 0
348 True = 1
349
350_active = []
351
352def _cleanup():
353 for inst in _active[:]:
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000354 res = inst.poll(_deadstate=sys.maxint)
355 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000356 try:
357 _active.remove(inst)
358 except ValueError:
359 # This can happen if two threads create a new Popen instance.
360 # It's harmless that it was already removed, so ignore.
361 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362
363PIPE = -1
364STDOUT = -2
365
366
Peter Astrand5f5e1412004-12-05 20:15:36 +0000367def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 """Run command with arguments. Wait for command to complete, then
369 return the returncode attribute.
370
371 The arguments are the same as for the Popen constructor. Example:
372
373 retcode = call(["ls", "-l"])
374 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000375 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376
377
Peter Astrand454f7672005-01-01 09:36:35 +0000378def check_call(*popenargs, **kwargs):
379 """Run command with arguments. Wait for command to complete. If
380 the exit code was zero then return, otherwise raise
381 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000382 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000383
384 The arguments are the same as for the Popen constructor. Example:
385
386 check_call(["ls", "-l"])
387 """
388 retcode = call(*popenargs, **kwargs)
389 cmd = kwargs.get("args")
390 if cmd is None:
391 cmd = popenargs[0]
392 if retcode:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000393 raise CalledProcessError(retcode, cmd)
Peter Astrand454f7672005-01-01 09:36:35 +0000394 return retcode
395
396
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397def list2cmdline(seq):
398 """
399 Translate a sequence of arguments into a command line
400 string, using the same rules as the MS C runtime:
401
402 1) Arguments are delimited by white space, which is either a
403 space or a tab.
404
405 2) A string surrounded by double quotation marks is
406 interpreted as a single argument, regardless of white space
407 contained within. A quoted string can be embedded in an
408 argument.
409
410 3) A double quotation mark preceded by a backslash is
411 interpreted as a literal double quotation mark.
412
413 4) Backslashes are interpreted literally, unless they
414 immediately precede a double quotation mark.
415
416 5) If backslashes immediately precede a double quotation mark,
417 every pair of backslashes is interpreted as a literal
418 backslash. If the number of backslashes is odd, the last
419 backslash escapes the next double quotation mark as
420 described in rule 3.
421 """
422
423 # See
424 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
425 result = []
426 needquote = False
427 for arg in seq:
428 bs_buf = []
429
430 # Add a space to separate this argument from the others
431 if result:
432 result.append(' ')
433
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000434 needquote = (" " in arg) or ("\t" in arg) or arg == ""
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 if needquote:
436 result.append('"')
437
438 for c in arg:
439 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000440 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 bs_buf.append(c)
442 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000443 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 result.append('\\' * len(bs_buf)*2)
445 bs_buf = []
446 result.append('\\"')
447 else:
448 # Normal char
449 if bs_buf:
450 result.extend(bs_buf)
451 bs_buf = []
452 result.append(c)
453
Tim Peterse718f612004-10-12 21:51:32 +0000454 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 if bs_buf:
456 result.extend(bs_buf)
457
458 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000459 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 result.append('"')
461
462 return ''.join(result)
463
464
465class Popen(object):
466 def __init__(self, args, bufsize=0, executable=None,
467 stdin=None, stdout=None, stderr=None,
468 preexec_fn=None, close_fds=False, shell=False,
469 cwd=None, env=None, universal_newlines=False,
470 startupinfo=None, creationflags=0):
471 """Create new Popen instance."""
472 _cleanup()
473
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474 self._child_created = False
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000475 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000476 raise TypeError("bufsize must be an integer")
477
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000479 if preexec_fn is not None:
480 raise ValueError("preexec_fn is not supported on Windows "
481 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000483 raise ValueError("close_fds is not supported on Windows "
484 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 else:
486 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000487 if startupinfo is not None:
488 raise ValueError("startupinfo is only supported on Windows "
489 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000491 raise ValueError("creationflags is only supported on Windows "
492 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493
Tim Peterse718f612004-10-12 21:51:32 +0000494 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 self.stdout = None
496 self.stderr = None
497 self.pid = None
498 self.returncode = None
499 self.universal_newlines = universal_newlines
500
501 # Input and output objects. The general principle is like
502 # this:
503 #
504 # Parent Child
505 # ------ -----
506 # p2cwrite ---stdin---> p2cread
507 # c2pread <--stdout--- c2pwrite
508 # errread <--stderr--- errwrite
509 #
510 # On POSIX, the child objects are file descriptors. On
511 # Windows, these are Windows file handles. The parent objects
512 # are file descriptors on both platforms. The parent objects
513 # are None when not using PIPEs. The child objects are None
514 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000515
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 (p2cread, p2cwrite,
517 c2pread, c2pwrite,
518 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
519
520 self._execute_child(args, executable, preexec_fn, close_fds,
521 cwd, env, universal_newlines,
522 startupinfo, creationflags, shell,
523 p2cread, p2cwrite,
524 c2pread, c2pwrite,
525 errread, errwrite)
526
Thomas Wouterscf297e42007-02-23 15:07:44 +0000527 # On Windows, you cannot just redirect one or two handles: You
528 # either have to redirect all three or none. If the subprocess
529 # user has only redirected one or two handles, we are
530 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000531 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000532 if mswindows:
533 if stdin is None and p2cwrite is not None:
534 os.close(p2cwrite)
535 p2cwrite = None
536 if stdout is None and c2pread is not None:
537 os.close(c2pread)
538 c2pread = None
539 if stderr is None and errread is not None:
540 os.close(errread)
541 errread = None
542
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000543 if bufsize == 0:
544 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000545 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000546 self.stdin = io.open(p2cwrite, 'wb', bufsize)
547 if self.universal_newlines:
548 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000549 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000550 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000552 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000553 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000554 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000556 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000557
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558
559 def _translate_newlines(self, data):
560 data = data.replace("\r\n", "\n")
561 data = data.replace("\r", "\n")
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000562 return str(data)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000564
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000566 if not self._child_created:
567 # We didn't get to successfully create a child process.
568 return
569 # In case the child hasn't been waited on, check if it's done.
570 self.poll(_deadstate=sys.maxint)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000571 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000572 # Child is still running, keep us alive until we can wait on it.
573 _active.append(self)
574
575
Peter Astrand23109f02005-03-03 20:28:59 +0000576 def communicate(self, input=None):
577 """Interact with process: Send data to stdin. Read data from
578 stdout and stderr, until end-of-file is reached. Wait for
579 process to terminate. The optional input argument should be a
580 string to be sent to the child process, or None, if no data
581 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000582
Peter Astrand23109f02005-03-03 20:28:59 +0000583 communicate() returns a tuple (stdout, stderr)."""
584
585 # Optimization: If we are only using one pipe, or no pipe at
586 # all, using select() or threads is unnecessary.
587 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000588 stdout = None
589 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000590 if self.stdin:
591 if input:
592 self.stdin.write(input)
593 self.stdin.close()
594 elif self.stdout:
595 stdout = self.stdout.read()
596 elif self.stderr:
597 stderr = self.stderr.read()
598 self.wait()
599 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000600
Peter Astrand23109f02005-03-03 20:28:59 +0000601 return self._communicate(input)
602
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000603
604 if mswindows:
605 #
606 # Windows methods
607 #
608 def _get_handles(self, stdin, stdout, stderr):
609 """Construct and return tupel with IO objects:
610 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
611 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000612 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000614
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000615 p2cread, p2cwrite = None, None
616 c2pread, c2pwrite = None, None
617 errread, errwrite = None, None
618
Peter Astrandd38ddf42005-02-10 08:32:50 +0000619 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000621 if p2cread is not None:
622 pass
623 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 p2cread, p2cwrite = CreatePipe(None, 0)
625 # Detach and turn into fd
626 p2cwrite = p2cwrite.Detach()
627 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000628 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 p2cread = msvcrt.get_osfhandle(stdin)
630 else:
631 # Assuming file-like object
632 p2cread = msvcrt.get_osfhandle(stdin.fileno())
633 p2cread = self._make_inheritable(p2cread)
634
Peter Astrandd38ddf42005-02-10 08:32:50 +0000635 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000637 if c2pwrite is not None:
638 pass
639 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 c2pread, c2pwrite = CreatePipe(None, 0)
641 # Detach and turn into fd
642 c2pread = c2pread.Detach()
643 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000644 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 c2pwrite = msvcrt.get_osfhandle(stdout)
646 else:
647 # Assuming file-like object
648 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
649 c2pwrite = self._make_inheritable(c2pwrite)
650
Peter Astrandd38ddf42005-02-10 08:32:50 +0000651 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000653 if errwrite is not None:
654 pass
655 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 errread, errwrite = CreatePipe(None, 0)
657 # Detach and turn into fd
658 errread = errread.Detach()
659 errread = msvcrt.open_osfhandle(errread, 0)
660 elif stderr == STDOUT:
661 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000662 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 errwrite = msvcrt.get_osfhandle(stderr)
664 else:
665 # Assuming file-like object
666 errwrite = msvcrt.get_osfhandle(stderr.fileno())
667 errwrite = self._make_inheritable(errwrite)
668
669 return (p2cread, p2cwrite,
670 c2pread, c2pwrite,
671 errread, errwrite)
672
673
674 def _make_inheritable(self, handle):
675 """Return a duplicate of handle, which is inheritable"""
676 return DuplicateHandle(GetCurrentProcess(), handle,
677 GetCurrentProcess(), 0, 1,
678 DUPLICATE_SAME_ACCESS)
679
680
681 def _find_w9xpopen(self):
682 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000683 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
684 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 if not os.path.exists(w9xpopen):
686 # Eeek - file-not-found - possibly an embedding
687 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000688 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
689 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000691 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
692 "needed for Popen to work with your "
693 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 return w9xpopen
695
Tim Peterse718f612004-10-12 21:51:32 +0000696
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697 def _execute_child(self, args, executable, preexec_fn, close_fds,
698 cwd, env, universal_newlines,
699 startupinfo, creationflags, shell,
700 p2cread, p2cwrite,
701 c2pread, c2pwrite,
702 errread, errwrite):
703 """Execute program (MS Windows version)"""
704
Guido van Rossumaf2362a2007-05-15 22:32:02 +0000705 if not isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 args = list2cmdline(args)
707
Peter Astrandc1d65362004-11-07 14:30:34 +0000708 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000709 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000710 startupinfo = STARTUPINFO()
711 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000712 startupinfo.dwFlags |= STARTF_USESTDHANDLES
713 startupinfo.hStdInput = p2cread
714 startupinfo.hStdOutput = c2pwrite
715 startupinfo.hStdError = errwrite
716
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000718 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
719 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720 comspec = os.environ.get("COMSPEC", "cmd.exe")
721 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000722 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000723 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724 # Win9x, or using command.com on NT. We need to
725 # use the w9xpopen intermediate program. For more
726 # information, see KB Q150956
727 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
728 w9xpopen = self._find_w9xpopen()
729 args = '"%s" %s' % (w9xpopen, args)
730 # Not passing CREATE_NEW_CONSOLE has been known to
731 # cause random failures on win9x. Specifically a
732 # dialog: "Your program accessed mem currently in
733 # use at xxx" and a hopeful warning about the
734 # stability of your system. Cost is Ctrl+C wont
735 # kill children.
736 creationflags |= CREATE_NEW_CONSOLE
737
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 # Start the process
739 try:
740 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000741 # no special security
742 None, None,
743 # must inherit handles to pass std
744 # handles
745 1,
746 creationflags,
747 env,
748 cwd,
749 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000750 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000751 # Translate pywintypes.error to WindowsError, which is
752 # a subclass of OSError. FIXME: We should really
753 # translate errno using _sys_errlist (or simliar), but
754 # how can this be done from Python?
755 raise WindowsError(*e.args)
756
757 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 self._handle = hp
760 self.pid = pid
761 ht.Close()
762
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000763 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 # handles that only the child should have open. You need
765 # to make sure that no handles to the write end of the
766 # output pipe are maintained in this process or else the
767 # pipe will not close when the child process exits and the
768 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000769 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000770 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000771 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000773 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774 errwrite.Close()
775
Tim Peterse718f612004-10-12 21:51:32 +0000776
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 """Check if child process has terminated. Returns returncode
779 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000780 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
782 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000783 return self.returncode
784
785
786 def wait(self):
787 """Wait for child process to terminate. Returns returncode
788 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000789 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 obj = WaitForSingleObject(self._handle, INFINITE)
791 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 return self.returncode
793
794
795 def _readerthread(self, fh, buffer):
796 buffer.append(fh.read())
797
798
Peter Astrand23109f02005-03-03 20:28:59 +0000799 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800 stdout = None # Return
801 stderr = None # Return
802
803 if self.stdout:
804 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000805 stdout_thread = threading.Thread(target=self._readerthread,
806 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 stdout_thread.setDaemon(True)
808 stdout_thread.start()
809 if self.stderr:
810 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000811 stderr_thread = threading.Thread(target=self._readerthread,
812 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 stderr_thread.setDaemon(True)
814 stderr_thread.start()
815
816 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000817 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818 self.stdin.write(input)
819 self.stdin.close()
820
821 if self.stdout:
822 stdout_thread.join()
823 if self.stderr:
824 stderr_thread.join()
825
826 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000827 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000829 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 stderr = stderr[0]
831
832 # Translate newlines, if requested. We cannot let the file
833 # object do the translation: It is based on stdio, which is
834 # impossible to combine with select (unless forcing no
835 # buffering).
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000836 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000837 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 stdout = self._translate_newlines(stdout)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000839 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 stderr = self._translate_newlines(stderr)
841
842 self.wait()
843 return (stdout, stderr)
844
845 else:
846 #
847 # POSIX methods
848 #
849 def _get_handles(self, stdin, stdout, stderr):
850 """Construct and return tupel with IO objects:
851 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
852 """
853 p2cread, p2cwrite = None, None
854 c2pread, c2pwrite = None, None
855 errread, errwrite = None, None
856
Peter Astrandd38ddf42005-02-10 08:32:50 +0000857 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 pass
859 elif stdin == PIPE:
860 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000861 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862 p2cread = stdin
863 else:
864 # Assuming file-like object
865 p2cread = stdin.fileno()
866
Peter Astrandd38ddf42005-02-10 08:32:50 +0000867 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 pass
869 elif stdout == PIPE:
870 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000871 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 c2pwrite = stdout
873 else:
874 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000875 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876
Peter Astrandd38ddf42005-02-10 08:32:50 +0000877 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000878 pass
879 elif stderr == PIPE:
880 errread, errwrite = os.pipe()
881 elif stderr == STDOUT:
882 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000883 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884 errwrite = stderr
885 else:
886 # Assuming file-like object
887 errwrite = stderr.fileno()
888
889 return (p2cread, p2cwrite,
890 c2pread, c2pwrite,
891 errread, errwrite)
892
893
894 def _set_cloexec_flag(self, fd):
895 try:
896 cloexec_flag = fcntl.FD_CLOEXEC
897 except AttributeError:
898 cloexec_flag = 1
899
900 old = fcntl.fcntl(fd, fcntl.F_GETFD)
901 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
902
903
904 def _close_fds(self, but):
Guido van Rossum805365e2007-05-07 22:24:25 +0000905 for i in range(3, MAXFD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000906 if i == but:
907 continue
908 try:
909 os.close(i)
910 except:
911 pass
Tim Peterse718f612004-10-12 21:51:32 +0000912
913
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914 def _execute_child(self, args, executable, preexec_fn, close_fds,
915 cwd, env, universal_newlines,
916 startupinfo, creationflags, shell,
917 p2cread, p2cwrite,
918 c2pread, c2pwrite,
919 errread, errwrite):
920 """Execute program (POSIX version)"""
921
Guido van Rossumaf2362a2007-05-15 22:32:02 +0000922 if isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000924 else:
925 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926
927 if shell:
928 args = ["/bin/sh", "-c"] + args
929
Peter Astrandd38ddf42005-02-10 08:32:50 +0000930 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 executable = args[0]
932
933 # For transferring possible exec failure from child to parent
934 # The first char specifies the exception type: 0 means
935 # OSError, 1 means some other error.
936 errpipe_read, errpipe_write = os.pipe()
937 self._set_cloexec_flag(errpipe_write)
938
939 self.pid = os.fork()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000940 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000941 if self.pid == 0:
942 # Child
943 try:
944 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +0000945 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000947 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000949 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 os.close(errread)
951 os.close(errpipe_read)
952
953 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +0000954 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000956 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000958 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 os.dup2(errwrite, 2)
960
Thomas Wouters89f507f2006-12-13 04:49:30 +0000961 # Close pipe fds. Make sure we don't close the same
962 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000963 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000964 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000965 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000966 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000967 if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000968 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969
970 # Close all other fds, if asked for
971 if close_fds:
972 self._close_fds(but=errpipe_write)
973
Peter Astrandd38ddf42005-02-10 08:32:50 +0000974 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 os.chdir(cwd)
976
977 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +0000978 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979
Peter Astrandd38ddf42005-02-10 08:32:50 +0000980 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000981 os.execvp(executable, args)
982 else:
983 os.execvpe(executable, args, env)
984
985 except:
986 exc_type, exc_value, tb = sys.exc_info()
987 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +0000988 exc_lines = traceback.format_exception(exc_type,
989 exc_value,
990 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000991 exc_value.child_traceback = ''.join(exc_lines)
992 os.write(errpipe_write, pickle.dumps(exc_value))
993
994 # This exitcode won't be reported to applications, so it
995 # really doesn't matter what we return.
996 os._exit(255)
997
998 # Parent
999 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001000 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001001 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001002 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001003 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001004 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001005 os.close(errwrite)
1006
1007 # Wait for exec to fail or succeed; possibly raising exception
1008 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1009 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001010 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001011 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012 child_exception = pickle.loads(data)
1013 raise child_exception
1014
1015
1016 def _handle_exitstatus(self, sts):
1017 if os.WIFSIGNALED(sts):
1018 self.returncode = -os.WTERMSIG(sts)
1019 elif os.WIFEXITED(sts):
1020 self.returncode = os.WEXITSTATUS(sts)
1021 else:
1022 # Should never happen
1023 raise RuntimeError("Unknown child exit status!")
1024
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001025
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001026 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 """Check if child process has terminated. Returns returncode
1028 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001029 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 try:
1031 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1032 if pid == self.pid:
1033 self._handle_exitstatus(sts)
1034 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001035 if _deadstate is not None:
1036 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001037 return self.returncode
1038
1039
1040 def wait(self):
1041 """Wait for child process to terminate. Returns returncode
1042 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001043 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044 pid, sts = os.waitpid(self.pid, 0)
1045 self._handle_exitstatus(sts)
1046 return self.returncode
1047
1048
Peter Astrand23109f02005-03-03 20:28:59 +00001049 def _communicate(self, input):
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001050 if isinstance(input, str): # Unicode
1051 input = input.encode("utf-8") # XXX What else?
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001052 read_set = []
1053 write_set = []
1054 stdout = None # Return
1055 stderr = None # Return
1056
1057 if self.stdin:
1058 # Flush stdio buffer. This might block, if the user has
1059 # been writing to .stdin in an uncontrolled fashion.
1060 self.stdin.flush()
1061 if input:
1062 write_set.append(self.stdin)
1063 else:
1064 self.stdin.close()
1065 if self.stdout:
1066 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001067 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068 if self.stderr:
1069 read_set.append(self.stderr)
1070 stderr = []
1071
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001072 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 while read_set or write_set:
1074 rlist, wlist, xlist = select.select(read_set, write_set, [])
1075
1076 if self.stdin in wlist:
1077 # When select has indicated that the file is writable,
1078 # we can write up to PIPE_BUF bytes without risk
1079 # blocking. POSIX defines PIPE_BUF >= 512
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001080 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512))
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001081 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001082 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 self.stdin.close()
1084 write_set.remove(self.stdin)
1085
1086 if self.stdout in rlist:
1087 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001088 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 self.stdout.close()
1090 read_set.remove(self.stdout)
1091 stdout.append(data)
1092
1093 if self.stderr in rlist:
1094 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001095 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096 self.stderr.close()
1097 read_set.remove(self.stderr)
1098 stderr.append(data)
1099
1100 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001101 if stdout is not None:
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001102 stdout = b''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001103 if stderr is not None:
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001104 stderr = b''.join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105
1106 # Translate newlines, if requested. We cannot let the file
1107 # object do the translation: It is based on stdio, which is
1108 # impossible to combine with select (unless forcing no
1109 # buffering).
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001110 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001111 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001112 stdout = self._translate_newlines(stdout)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001113 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114 stderr = self._translate_newlines(stderr)
1115
1116 self.wait()
1117 return (stdout, stderr)
1118
1119
1120def _demo_posix():
1121 #
1122 # Example 1: Simple redirection: Get process list
1123 #
1124 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001125 print("Process list:")
1126 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001127
1128 #
1129 # Example 2: Change uid before executing child
1130 #
1131 if os.getuid() == 0:
1132 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1133 p.wait()
1134
1135 #
1136 # Example 3: Connecting several subprocesses
1137 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001138 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001139 p1 = Popen(["dmesg"], stdout=PIPE)
1140 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001141 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001142
1143 #
1144 # Example 4: Catch execution error
1145 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001146 print()
1147 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001148 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001149 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001150 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001151 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001152 print("The file didn't exist. I thought so...")
1153 print("Child traceback:")
1154 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001156 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001157 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001158 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001159
1160
1161def _demo_windows():
1162 #
1163 # Example 1: Connecting several subprocesses
1164 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001165 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001166 p1 = Popen("set", stdout=PIPE, shell=True)
1167 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001168 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001169
1170 #
1171 # Example 2: Simple execution of program
1172 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001173 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174 p = Popen("calc")
1175 p.wait()
1176
1177
1178if __name__ == "__main__":
1179 if mswindows:
1180 _demo_windows()
1181 else:
1182 _demo_posix()