blob: 2d02df65cae3e6bb4714559da809a87853c622b7 [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:
249 print >>sys.stderr, "Child was terminated by signal", -retcode
250 else:
251 print >>sys.stderr, "Child returned", retcode
252except OSError, e:
253 print >>sys.stderr, "Execution failed:", e
254
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
289import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290import traceback
291
Peter Astrand454f7672005-01-01 09:36:35 +0000292# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000293class CalledProcessError(Exception):
Peter Astrand454f7672005-01-01 09:36:35 +0000294 """This exception is raised when a process run by check_call() returns
295 a non-zero exit status. The exit status will be stored in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000296 returncode attribute."""
297 def __init__(self, returncode, cmd):
298 self.returncode = returncode
299 self.cmd = cmd
300 def __str__(self):
301 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
302
Peter Astrand454f7672005-01-01 09:36:35 +0000303
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304if mswindows:
305 import threading
306 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000307 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000309 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
310 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
311 from win32api import GetCurrentProcess, DuplicateHandle, \
312 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000313 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000315 from win32process import CreateProcess, STARTUPINFO, \
316 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000317 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000319 else:
320 from _subprocess import *
321 class STARTUPINFO:
322 dwFlags = 0
323 hStdInput = None
324 hStdOutput = None
325 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000326 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000327 class pywintypes:
328 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329else:
330 import select
331 import errno
332 import fcntl
333 import pickle
334
Peter Astrand454f7672005-01-01 09:36:35 +0000335__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336
337try:
338 MAXFD = os.sysconf("SC_OPEN_MAX")
339except:
340 MAXFD = 256
341
342# True/False does not exist on 2.2.0
343try:
344 False
345except NameError:
346 False = 0
347 True = 1
348
349_active = []
350
351def _cleanup():
352 for inst in _active[:]:
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000353 res = inst.poll(_deadstate=sys.maxint)
354 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000355 try:
356 _active.remove(inst)
357 except ValueError:
358 # This can happen if two threads create a new Popen instance.
359 # It's harmless that it was already removed, so ignore.
360 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361
362PIPE = -1
363STDOUT = -2
364
365
Peter Astrand5f5e1412004-12-05 20:15:36 +0000366def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367 """Run command with arguments. Wait for command to complete, then
368 return the returncode attribute.
369
370 The arguments are the same as for the Popen constructor. Example:
371
372 retcode = call(["ls", "-l"])
373 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000374 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375
376
Peter Astrand454f7672005-01-01 09:36:35 +0000377def check_call(*popenargs, **kwargs):
378 """Run command with arguments. Wait for command to complete. If
379 the exit code was zero then return, otherwise raise
380 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000381 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000382
383 The arguments are the same as for the Popen constructor. Example:
384
385 check_call(["ls", "-l"])
386 """
387 retcode = call(*popenargs, **kwargs)
388 cmd = kwargs.get("args")
389 if cmd is None:
390 cmd = popenargs[0]
391 if retcode:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000392 raise CalledProcessError(retcode, cmd)
Peter Astrand454f7672005-01-01 09:36:35 +0000393 return retcode
394
395
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396def list2cmdline(seq):
397 """
398 Translate a sequence of arguments into a command line
399 string, using the same rules as the MS C runtime:
400
401 1) Arguments are delimited by white space, which is either a
402 space or a tab.
403
404 2) A string surrounded by double quotation marks is
405 interpreted as a single argument, regardless of white space
406 contained within. A quoted string can be embedded in an
407 argument.
408
409 3) A double quotation mark preceded by a backslash is
410 interpreted as a literal double quotation mark.
411
412 4) Backslashes are interpreted literally, unless they
413 immediately precede a double quotation mark.
414
415 5) If backslashes immediately precede a double quotation mark,
416 every pair of backslashes is interpreted as a literal
417 backslash. If the number of backslashes is odd, the last
418 backslash escapes the next double quotation mark as
419 described in rule 3.
420 """
421
422 # See
423 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
424 result = []
425 needquote = False
426 for arg in seq:
427 bs_buf = []
428
429 # Add a space to separate this argument from the others
430 if result:
431 result.append(' ')
432
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000433 needquote = (" " in arg) or ("\t" in arg) or arg == ""
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434 if needquote:
435 result.append('"')
436
437 for c in arg:
438 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000439 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 bs_buf.append(c)
441 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000442 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 result.append('\\' * len(bs_buf)*2)
444 bs_buf = []
445 result.append('\\"')
446 else:
447 # Normal char
448 if bs_buf:
449 result.extend(bs_buf)
450 bs_buf = []
451 result.append(c)
452
Tim Peterse718f612004-10-12 21:51:32 +0000453 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 if bs_buf:
455 result.extend(bs_buf)
456
457 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000458 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 result.append('"')
460
461 return ''.join(result)
462
463
464class Popen(object):
465 def __init__(self, args, bufsize=0, executable=None,
466 stdin=None, stdout=None, stderr=None,
467 preexec_fn=None, close_fds=False, shell=False,
468 cwd=None, env=None, universal_newlines=False,
469 startupinfo=None, creationflags=0):
470 """Create new Popen instance."""
471 _cleanup()
472
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473 self._child_created = False
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000474 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000475 raise TypeError("bufsize must be an integer")
476
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000478 if preexec_fn is not None:
479 raise ValueError("preexec_fn is not supported on Windows "
480 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000482 raise ValueError("close_fds is not supported on Windows "
483 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 else:
485 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000486 if startupinfo is not None:
487 raise ValueError("startupinfo is only supported on Windows "
488 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000490 raise ValueError("creationflags is only supported on Windows "
491 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
Tim Peterse718f612004-10-12 21:51:32 +0000493 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 self.stdout = None
495 self.stderr = None
496 self.pid = None
497 self.returncode = None
498 self.universal_newlines = universal_newlines
499
500 # Input and output objects. The general principle is like
501 # this:
502 #
503 # Parent Child
504 # ------ -----
505 # p2cwrite ---stdin---> p2cread
506 # c2pread <--stdout--- c2pwrite
507 # errread <--stderr--- errwrite
508 #
509 # On POSIX, the child objects are file descriptors. On
510 # Windows, these are Windows file handles. The parent objects
511 # are file descriptors on both platforms. The parent objects
512 # are None when not using PIPEs. The child objects are None
513 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000514
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 (p2cread, p2cwrite,
516 c2pread, c2pwrite,
517 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
518
519 self._execute_child(args, executable, preexec_fn, close_fds,
520 cwd, env, universal_newlines,
521 startupinfo, creationflags, shell,
522 p2cread, p2cwrite,
523 c2pread, c2pwrite,
524 errread, errwrite)
525
Thomas Wouterscf297e42007-02-23 15:07:44 +0000526 # On Windows, you cannot just redirect one or two handles: You
527 # either have to redirect all three or none. If the subprocess
528 # user has only redirected one or two handles, we are
529 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000531 if mswindows:
532 if stdin is None and p2cwrite is not None:
533 os.close(p2cwrite)
534 p2cwrite = None
535 if stdout is None and c2pread is not None:
536 os.close(c2pread)
537 c2pread = None
538 if stderr is None and errread is not None:
539 os.close(errread)
540 errread = None
541
542 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000544 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 if universal_newlines:
546 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
547 else:
548 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000549 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 if universal_newlines:
551 self.stderr = os.fdopen(errread, 'rU', bufsize)
552 else:
553 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000554
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
556 def _translate_newlines(self, data):
557 data = data.replace("\r\n", "\n")
558 data = data.replace("\r", "\n")
559 return data
560
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000561
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 if not self._child_created:
564 # We didn't get to successfully create a child process.
565 return
566 # In case the child hasn't been waited on, check if it's done.
567 self.poll(_deadstate=sys.maxint)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000568 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000569 # Child is still running, keep us alive until we can wait on it.
570 _active.append(self)
571
572
Peter Astrand23109f02005-03-03 20:28:59 +0000573 def communicate(self, input=None):
574 """Interact with process: Send data to stdin. Read data from
575 stdout and stderr, until end-of-file is reached. Wait for
576 process to terminate. The optional input argument should be a
577 string to be sent to the child process, or None, if no data
578 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000579
Peter Astrand23109f02005-03-03 20:28:59 +0000580 communicate() returns a tuple (stdout, stderr)."""
581
582 # Optimization: If we are only using one pipe, or no pipe at
583 # all, using select() or threads is unnecessary.
584 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000585 stdout = None
586 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000587 if self.stdin:
588 if input:
589 self.stdin.write(input)
590 self.stdin.close()
591 elif self.stdout:
592 stdout = self.stdout.read()
593 elif self.stderr:
594 stderr = self.stderr.read()
595 self.wait()
596 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000597
Peter Astrand23109f02005-03-03 20:28:59 +0000598 return self._communicate(input)
599
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600
601 if mswindows:
602 #
603 # Windows methods
604 #
605 def _get_handles(self, stdin, stdout, stderr):
606 """Construct and return tupel with IO objects:
607 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
608 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000609 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000611
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 p2cread, p2cwrite = None, None
613 c2pread, c2pwrite = None, None
614 errread, errwrite = None, None
615
Peter Astrandd38ddf42005-02-10 08:32:50 +0000616 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000618 if p2cread is not None:
619 pass
620 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 p2cread, p2cwrite = CreatePipe(None, 0)
622 # Detach and turn into fd
623 p2cwrite = p2cwrite.Detach()
624 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000625 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626 p2cread = msvcrt.get_osfhandle(stdin)
627 else:
628 # Assuming file-like object
629 p2cread = msvcrt.get_osfhandle(stdin.fileno())
630 p2cread = self._make_inheritable(p2cread)
631
Peter Astrandd38ddf42005-02-10 08:32:50 +0000632 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000633 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000634 if c2pwrite is not None:
635 pass
636 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637 c2pread, c2pwrite = CreatePipe(None, 0)
638 # Detach and turn into fd
639 c2pread = c2pread.Detach()
640 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000641 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 c2pwrite = msvcrt.get_osfhandle(stdout)
643 else:
644 # Assuming file-like object
645 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
646 c2pwrite = self._make_inheritable(c2pwrite)
647
Peter Astrandd38ddf42005-02-10 08:32:50 +0000648 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000649 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000650 if errwrite is not None:
651 pass
652 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000653 errread, errwrite = CreatePipe(None, 0)
654 # Detach and turn into fd
655 errread = errread.Detach()
656 errread = msvcrt.open_osfhandle(errread, 0)
657 elif stderr == STDOUT:
658 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000659 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660 errwrite = msvcrt.get_osfhandle(stderr)
661 else:
662 # Assuming file-like object
663 errwrite = msvcrt.get_osfhandle(stderr.fileno())
664 errwrite = self._make_inheritable(errwrite)
665
666 return (p2cread, p2cwrite,
667 c2pread, c2pwrite,
668 errread, errwrite)
669
670
671 def _make_inheritable(self, handle):
672 """Return a duplicate of handle, which is inheritable"""
673 return DuplicateHandle(GetCurrentProcess(), handle,
674 GetCurrentProcess(), 0, 1,
675 DUPLICATE_SAME_ACCESS)
676
677
678 def _find_w9xpopen(self):
679 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000680 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
681 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 if not os.path.exists(w9xpopen):
683 # Eeek - file-not-found - possibly an embedding
684 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000685 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
686 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000688 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
689 "needed for Popen to work with your "
690 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000691 return w9xpopen
692
Tim Peterse718f612004-10-12 21:51:32 +0000693
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 def _execute_child(self, args, executable, preexec_fn, close_fds,
695 cwd, env, universal_newlines,
696 startupinfo, creationflags, shell,
697 p2cread, p2cwrite,
698 c2pread, c2pwrite,
699 errread, errwrite):
700 """Execute program (MS Windows version)"""
701
Guido van Rossumaf2362a2007-05-15 22:32:02 +0000702 if not isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 args = list2cmdline(args)
704
Peter Astrandc1d65362004-11-07 14:30:34 +0000705 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000706 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000707 startupinfo = STARTUPINFO()
708 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000709 startupinfo.dwFlags |= STARTF_USESTDHANDLES
710 startupinfo.hStdInput = p2cread
711 startupinfo.hStdOutput = c2pwrite
712 startupinfo.hStdError = errwrite
713
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000715 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
716 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 comspec = os.environ.get("COMSPEC", "cmd.exe")
718 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000719 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000720 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721 # Win9x, or using command.com on NT. We need to
722 # use the w9xpopen intermediate program. For more
723 # information, see KB Q150956
724 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
725 w9xpopen = self._find_w9xpopen()
726 args = '"%s" %s' % (w9xpopen, args)
727 # Not passing CREATE_NEW_CONSOLE has been known to
728 # cause random failures on win9x. Specifically a
729 # dialog: "Your program accessed mem currently in
730 # use at xxx" and a hopeful warning about the
731 # stability of your system. Cost is Ctrl+C wont
732 # kill children.
733 creationflags |= CREATE_NEW_CONSOLE
734
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735 # Start the process
736 try:
737 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000738 # no special security
739 None, None,
740 # must inherit handles to pass std
741 # handles
742 1,
743 creationflags,
744 env,
745 cwd,
746 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000747 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 # Translate pywintypes.error to WindowsError, which is
749 # a subclass of OSError. FIXME: We should really
750 # translate errno using _sys_errlist (or simliar), but
751 # how can this be done from Python?
752 raise WindowsError(*e.args)
753
754 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 self._handle = hp
757 self.pid = pid
758 ht.Close()
759
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000760 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 # handles that only the child should have open. You need
762 # to make sure that no handles to the write end of the
763 # output pipe are maintained in this process or else the
764 # pipe will not close when the child process exits and the
765 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000766 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000768 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000770 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771 errwrite.Close()
772
Tim Peterse718f612004-10-12 21:51:32 +0000773
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 """Check if child process has terminated. Returns returncode
776 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000777 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
779 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 return self.returncode
781
782
783 def wait(self):
784 """Wait for child process to terminate. Returns returncode
785 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000786 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 obj = WaitForSingleObject(self._handle, INFINITE)
788 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000789 return self.returncode
790
791
792 def _readerthread(self, fh, buffer):
793 buffer.append(fh.read())
794
795
Peter Astrand23109f02005-03-03 20:28:59 +0000796 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797 stdout = None # Return
798 stderr = None # Return
799
800 if self.stdout:
801 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000802 stdout_thread = threading.Thread(target=self._readerthread,
803 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 stdout_thread.setDaemon(True)
805 stdout_thread.start()
806 if self.stderr:
807 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000808 stderr_thread = threading.Thread(target=self._readerthread,
809 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000810 stderr_thread.setDaemon(True)
811 stderr_thread.start()
812
813 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000814 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 self.stdin.write(input)
816 self.stdin.close()
817
818 if self.stdout:
819 stdout_thread.join()
820 if self.stderr:
821 stderr_thread.join()
822
823 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000824 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000826 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 stderr = stderr[0]
828
829 # Translate newlines, if requested. We cannot let the file
830 # object do the translation: It is based on stdio, which is
831 # impossible to combine with select (unless forcing no
832 # buffering).
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000833 if self.universal_newlines:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 if stdout:
835 stdout = self._translate_newlines(stdout)
836 if stderr:
837 stderr = self._translate_newlines(stderr)
838
839 self.wait()
840 return (stdout, stderr)
841
842 else:
843 #
844 # POSIX methods
845 #
846 def _get_handles(self, stdin, stdout, stderr):
847 """Construct and return tupel with IO objects:
848 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
849 """
850 p2cread, p2cwrite = None, None
851 c2pread, c2pwrite = None, None
852 errread, errwrite = None, None
853
Peter Astrandd38ddf42005-02-10 08:32:50 +0000854 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 pass
856 elif stdin == PIPE:
857 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000858 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000859 p2cread = stdin
860 else:
861 # Assuming file-like object
862 p2cread = stdin.fileno()
863
Peter Astrandd38ddf42005-02-10 08:32:50 +0000864 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865 pass
866 elif stdout == PIPE:
867 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000868 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 c2pwrite = stdout
870 else:
871 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000872 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873
Peter Astrandd38ddf42005-02-10 08:32:50 +0000874 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000875 pass
876 elif stderr == PIPE:
877 errread, errwrite = os.pipe()
878 elif stderr == STDOUT:
879 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000880 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 errwrite = stderr
882 else:
883 # Assuming file-like object
884 errwrite = stderr.fileno()
885
886 return (p2cread, p2cwrite,
887 c2pread, c2pwrite,
888 errread, errwrite)
889
890
891 def _set_cloexec_flag(self, fd):
892 try:
893 cloexec_flag = fcntl.FD_CLOEXEC
894 except AttributeError:
895 cloexec_flag = 1
896
897 old = fcntl.fcntl(fd, fcntl.F_GETFD)
898 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
899
900
901 def _close_fds(self, but):
Guido van Rossum805365e2007-05-07 22:24:25 +0000902 for i in range(3, MAXFD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000903 if i == but:
904 continue
905 try:
906 os.close(i)
907 except:
908 pass
Tim Peterse718f612004-10-12 21:51:32 +0000909
910
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 def _execute_child(self, args, executable, preexec_fn, close_fds,
912 cwd, env, universal_newlines,
913 startupinfo, creationflags, shell,
914 p2cread, p2cwrite,
915 c2pread, c2pwrite,
916 errread, errwrite):
917 """Execute program (POSIX version)"""
918
Guido van Rossumaf2362a2007-05-15 22:32:02 +0000919 if isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921 else:
922 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923
924 if shell:
925 args = ["/bin/sh", "-c"] + args
926
Peter Astrandd38ddf42005-02-10 08:32:50 +0000927 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000928 executable = args[0]
929
930 # For transferring possible exec failure from child to parent
931 # The first char specifies the exception type: 0 means
932 # OSError, 1 means some other error.
933 errpipe_read, errpipe_write = os.pipe()
934 self._set_cloexec_flag(errpipe_write)
935
936 self.pid = os.fork()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000937 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938 if self.pid == 0:
939 # Child
940 try:
941 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +0000942 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000944 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000946 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947 os.close(errread)
948 os.close(errpipe_read)
949
950 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +0000951 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000952 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000953 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000954 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000955 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000956 os.dup2(errwrite, 2)
957
Thomas Wouters89f507f2006-12-13 04:49:30 +0000958 # Close pipe fds. Make sure we don't close the same
959 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000960 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000961 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000962 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000963 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000964 if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000965 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
967 # Close all other fds, if asked for
968 if close_fds:
969 self._close_fds(but=errpipe_write)
970
Peter Astrandd38ddf42005-02-10 08:32:50 +0000971 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000972 os.chdir(cwd)
973
974 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +0000975 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976
Peter Astrandd38ddf42005-02-10 08:32:50 +0000977 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978 os.execvp(executable, args)
979 else:
980 os.execvpe(executable, args, env)
981
982 except:
983 exc_type, exc_value, tb = sys.exc_info()
984 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +0000985 exc_lines = traceback.format_exception(exc_type,
986 exc_value,
987 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988 exc_value.child_traceback = ''.join(exc_lines)
989 os.write(errpipe_write, pickle.dumps(exc_value))
990
991 # This exitcode won't be reported to applications, so it
992 # really doesn't matter what we return.
993 os._exit(255)
994
995 # Parent
996 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000997 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000999 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001001 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 os.close(errwrite)
1003
1004 # Wait for exec to fail or succeed; possibly raising exception
1005 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1006 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001007 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001008 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001009 child_exception = pickle.loads(data)
1010 raise child_exception
1011
1012
1013 def _handle_exitstatus(self, sts):
1014 if os.WIFSIGNALED(sts):
1015 self.returncode = -os.WTERMSIG(sts)
1016 elif os.WIFEXITED(sts):
1017 self.returncode = os.WEXITSTATUS(sts)
1018 else:
1019 # Should never happen
1020 raise RuntimeError("Unknown child exit status!")
1021
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024 """Check if child process has terminated. Returns returncode
1025 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001026 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 try:
1028 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1029 if pid == self.pid:
1030 self._handle_exitstatus(sts)
1031 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001032 if _deadstate is not None:
1033 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034 return self.returncode
1035
1036
1037 def wait(self):
1038 """Wait for child process to terminate. Returns returncode
1039 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001040 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001041 pid, sts = os.waitpid(self.pid, 0)
1042 self._handle_exitstatus(sts)
1043 return self.returncode
1044
1045
Peter Astrand23109f02005-03-03 20:28:59 +00001046 def _communicate(self, input):
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001047 if isinstance(input, str): # Unicode
1048 input = input.encode("utf-8") # XXX What else?
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049 read_set = []
1050 write_set = []
1051 stdout = None # Return
1052 stderr = None # Return
1053
1054 if self.stdin:
1055 # Flush stdio buffer. This might block, if the user has
1056 # been writing to .stdin in an uncontrolled fashion.
1057 self.stdin.flush()
1058 if input:
1059 write_set.append(self.stdin)
1060 else:
1061 self.stdin.close()
1062 if self.stdout:
1063 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001064 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001065 if self.stderr:
1066 read_set.append(self.stderr)
1067 stderr = []
1068
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001069 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001070 while read_set or write_set:
1071 rlist, wlist, xlist = select.select(read_set, write_set, [])
1072
1073 if self.stdin in wlist:
1074 # When select has indicated that the file is writable,
1075 # we can write up to PIPE_BUF bytes without risk
1076 # blocking. POSIX defines PIPE_BUF >= 512
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001077 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512))
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001078 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001079 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001080 self.stdin.close()
1081 write_set.remove(self.stdin)
1082
1083 if self.stdout in rlist:
1084 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001085 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086 self.stdout.close()
1087 read_set.remove(self.stdout)
1088 stdout.append(data)
1089
1090 if self.stderr in rlist:
1091 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001092 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093 self.stderr.close()
1094 read_set.remove(self.stderr)
1095 stderr.append(data)
1096
1097 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001098 if stdout is not None:
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001099 stdout = b''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001100 if stderr is not None:
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001101 stderr = b''.join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102
1103 # Translate newlines, if requested. We cannot let the file
1104 # object do the translation: It is based on stdio, which is
1105 # impossible to combine with select (unless forcing no
1106 # buffering).
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001107 if self.universal_newlines:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108 if stdout:
1109 stdout = self._translate_newlines(stdout)
1110 if stderr:
1111 stderr = self._translate_newlines(stderr)
1112
1113 self.wait()
1114 return (stdout, stderr)
1115
1116
1117def _demo_posix():
1118 #
1119 # Example 1: Simple redirection: Get process list
1120 #
1121 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001122 print("Process list:")
1123 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001124
1125 #
1126 # Example 2: Change uid before executing child
1127 #
1128 if os.getuid() == 0:
1129 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1130 p.wait()
1131
1132 #
1133 # Example 3: Connecting several subprocesses
1134 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001135 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001136 p1 = Popen(["dmesg"], stdout=PIPE)
1137 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001138 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001139
1140 #
1141 # Example 4: Catch execution error
1142 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001143 print()
1144 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001145 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001146 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001147 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001148 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001149 print("The file didn't exist. I thought so...")
1150 print("Child traceback:")
1151 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001152 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001153 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001154 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001155 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001156
1157
1158def _demo_windows():
1159 #
1160 # Example 1: Connecting several subprocesses
1161 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001162 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001163 p1 = Popen("set", stdout=PIPE, shell=True)
1164 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001165 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001166
1167 #
1168 # Example 2: Simple execution of program
1169 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001170 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 p = Popen("calc")
1172 p.wait()
1173
1174
1175if __name__ == "__main__":
1176 if mswindows:
1177 _demo_windows()
1178 else:
1179 _demo_posix()