blob: 783f61711a77620e5aec2cef496cfdbef666d44a [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#
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se>
8#
Peter Astrand69bf13f2005-02-14 08:56:32 +00009# Licensed to PSF under a Contributor Agreement.
10#
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011# By obtaining, using, and/or copying this software and/or its
12# associated documentation, you agree that you have read, understood,
13# and will comply with the following terms and conditions:
14#
15# Permission to use, copy, modify, and distribute this software and
16# its associated documentation for any purpose and without fee is
17# hereby granted, provided that the above copyright notice appears in
18# all copies, and that both that copyright notice and this permission
19# notice appear in supporting documentation, and that the name of the
20# author not be used in advertising or publicity pertaining to
21# distribution of the software without specific, written prior
22# permission.
23#
24# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
25# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
26# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
27# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
28# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
29# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
30# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
31
Raymond Hettinger837dd932004-10-17 16:36:53 +000032r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000034This module allows you to spawn processes, connect to their
35input/output/error pipes, and obtain their return codes. This module
36intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000037
38os.system
39os.spawn*
40os.popen*
41popen2.*
42commands.*
43
44Information about how the subprocess module can be used to replace these
45modules and functions can be found below.
46
47
48
49Using the subprocess module
50===========================
51This module defines one class called Popen:
52
53class Popen(args, bufsize=0, executable=None,
54 stdin=None, stdout=None, stderr=None,
55 preexec_fn=None, close_fds=False, shell=False,
56 cwd=None, env=None, universal_newlines=False,
57 startupinfo=None, creationflags=0):
58
59
60Arguments are:
61
62args should be a string, or a sequence of program arguments. The
63program to execute is normally the first item in the args sequence or
64string, but can be explicitly set by using the executable argument.
65
66On UNIX, with shell=False (default): In this case, the Popen class
67uses os.execvp() to execute the child program. args should normally
68be a sequence. A string will be treated as a sequence with the string
69as the only item (the program to execute).
70
71On UNIX, with shell=True: If args is a string, it specifies the
72command string to execute through the shell. If args is a sequence,
73the first item specifies the command string, and any additional items
74will be treated as additional shell arguments.
75
76On Windows: the Popen class uses CreateProcess() to execute the child
77program, which operates on strings. If args is a sequence, it will be
78converted to a string using the list2cmdline method. Please note that
79not all MS Windows applications interpret the command line the same
80way: The list2cmdline is designed for applications using the same
81rules as the MS C runtime.
82
83bufsize, if given, has the same meaning as the corresponding argument
84to the built-in open() function: 0 means unbuffered, 1 means line
85buffered, any other positive value means use a buffer of
86(approximately) that size. A negative bufsize means to use the system
87default, which usually means fully buffered. The default value for
88bufsize is 0 (unbuffered).
89
90stdin, stdout and stderr specify the executed programs' standard
91input, standard output and standard error file handles, respectively.
92Valid values are PIPE, an existing file descriptor (a positive
93integer), an existing file object, and None. PIPE indicates that a
94new pipe to the child should be created. With None, no redirection
95will occur; the child's file handles will be inherited from the
96parent. Additionally, stderr can be STDOUT, which indicates that the
97stderr data from the applications should be captured into the same
98file handle as for stdout.
99
100If preexec_fn is set to a callable object, this object will be called
101in the child process just before the child is executed.
102
103If close_fds is true, all file descriptors except 0, 1 and 2 will be
104closed before the child process is executed.
105
106if shell is true, the specified command will be executed through the
107shell.
108
109If cwd is not None, the current directory will be changed to cwd
110before the child is executed.
111
112If env is not None, it defines the environment variables for the new
113process.
114
115If universal_newlines is true, the file objects stdout and stderr are
116opened as a text files, but lines may be terminated by any of '\n',
117the Unix end-of-line convention, '\r', the Macintosh convention or
118'\r\n', the Windows convention. All of these external representations
119are seen as '\n' by the Python program. Note: This feature is only
120available if Python is built with universal newline support (the
121default). Also, the newlines attribute of the file objects stdout,
122stdin and stderr are not updated by the communicate() method.
123
124The startupinfo and creationflags, if given, will be passed to the
125underlying CreateProcess() function. They can specify things such as
126appearance of the main window and priority for the new process.
127(Windows only)
128
129
130This module also defines two shortcut functions:
131
Peter Astrand5f5e1412004-12-05 20:15:36 +0000132call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000133 Run command with arguments. Wait for command to complete, then
134 return the returncode attribute.
135
136 The arguments are the same as for the Popen constructor. Example:
137
138 retcode = call(["ls", "-l"])
139
Peter Astrand454f7672005-01-01 09:36:35 +0000140check_call(*popenargs, **kwargs):
141 Run command with arguments. Wait for command to complete. If the
142 exit code was zero then return, otherwise raise
143 CalledProcessError. The CalledProcessError object will have the
144 return code in the errno attribute.
145
146 The arguments are the same as for the Popen constructor. Example:
147
148 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000149
150Exceptions
151----------
152Exceptions raised in the child process, before the new program has
153started to execute, will be re-raised in the parent. Additionally,
154the exception object will have one extra attribute called
155'child_traceback', which is a string containing traceback information
156from the childs point of view.
157
158The most common exception raised is OSError. This occurs, for
159example, when trying to execute a non-existent file. Applications
160should prepare for OSErrors.
161
162A ValueError will be raised if Popen is called with invalid arguments.
163
Peter Astrand454f7672005-01-01 09:36:35 +0000164check_call() will raise CalledProcessError, which is a subclass of
165OSError, if the called process returns a non-zero return code.
166
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167
168Security
169--------
170Unlike some other popen functions, this implementation will never call
171/bin/sh implicitly. This means that all characters, including shell
172metacharacters, can safely be passed to child processes.
173
174
175Popen objects
176=============
177Instances of the Popen class have the following methods:
178
179poll()
180 Check if child process has terminated. Returns returncode
181 attribute.
182
183wait()
184 Wait for child process to terminate. Returns returncode attribute.
185
186communicate(input=None)
187 Interact with process: Send data to stdin. Read data from stdout
188 and stderr, until end-of-file is reached. Wait for process to
189 terminate. The optional stdin argument should be a string to be
190 sent to the child process, or None, if no data should be sent to
191 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000192
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000193 communicate() returns a tuple (stdout, stderr).
194
195 Note: The data read is buffered in memory, so do not use this
196 method if the data size is large or unlimited.
197
198The following attributes are also available:
199
200stdin
201 If the stdin argument is PIPE, this attribute is a file object
202 that provides input to the child process. Otherwise, it is None.
203
204stdout
205 If the stdout argument is PIPE, this attribute is a file object
206 that provides output from the child process. Otherwise, it is
207 None.
208
209stderr
210 If the stderr argument is PIPE, this attribute is file object that
211 provides error output from the child process. Otherwise, it is
212 None.
213
214pid
215 The process ID of the child process.
216
217returncode
218 The child return code. A None value indicates that the process
219 hasn't terminated yet. A negative value -N indicates that the
220 child was terminated by signal N (UNIX only).
221
222
223Replacing older functions with the subprocess module
224====================================================
225In this section, "a ==> b" means that b can be used as a replacement
226for a.
227
228Note: All functions in this section fail (more or less) silently if
229the executed program cannot be found; this module raises an OSError
230exception.
231
232In the following examples, we assume that the subprocess module is
233imported with "from subprocess import *".
234
235
236Replacing /bin/sh shell backquote
237---------------------------------
238output=`mycmd myarg`
239==>
240output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
241
242
243Replacing shell pipe line
244-------------------------
245output=`dmesg | grep hda`
246==>
247p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000248p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000249output = p2.communicate()[0]
250
251
252Replacing os.system()
253---------------------
254sts = os.system("mycmd" + " myarg")
255==>
256p = Popen("mycmd" + " myarg", shell=True)
257sts = os.waitpid(p.pid, 0)
258
259Note:
260
261* Calling the program through the shell is usually not required.
262
263* It's easier to look at the returncode attribute than the
264 exitstatus.
265
266A more real-world example would look like this:
267
268try:
269 retcode = call("mycmd" + " myarg", shell=True)
270 if retcode < 0:
271 print >>sys.stderr, "Child was terminated by signal", -retcode
272 else:
273 print >>sys.stderr, "Child returned", retcode
274except OSError, e:
275 print >>sys.stderr, "Execution failed:", e
276
277
278Replacing os.spawn*
279-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000280P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
283==>
284pid = Popen(["/bin/mycmd", "myarg"]).pid
285
286
287P_WAIT example:
288
289retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
290==>
291retcode = call(["/bin/mycmd", "myarg"])
292
293
Tim Peterse718f612004-10-12 21:51:32 +0000294Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295
296os.spawnvp(os.P_NOWAIT, path, args)
297==>
298Popen([path] + args[1:])
299
300
Tim Peterse718f612004-10-12 21:51:32 +0000301Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302
303os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
304==>
305Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
306
307
Tim Peterse718f612004-10-12 21:51:32 +0000308Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309-------------------
310pipe = os.popen(cmd, mode='r', bufsize)
311==>
312pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
313
314pipe = os.popen(cmd, mode='w', bufsize)
315==>
316pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
317
318
319(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
320==>
321p = Popen(cmd, shell=True, bufsize=bufsize,
322 stdin=PIPE, stdout=PIPE, close_fds=True)
323(child_stdin, child_stdout) = (p.stdin, p.stdout)
324
325
326(child_stdin,
327 child_stdout,
328 child_stderr) = os.popen3(cmd, mode, bufsize)
329==>
330p = Popen(cmd, shell=True, bufsize=bufsize,
331 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
332(child_stdin,
333 child_stdout,
334 child_stderr) = (p.stdin, p.stdout, p.stderr)
335
336
337(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
338==>
339p = Popen(cmd, shell=True, bufsize=bufsize,
340 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
341(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
342
343
344Replacing popen2.*
345------------------
346Note: If the cmd argument to popen2 functions is a string, the command
347is executed through /bin/sh. If it is a list, the command is directly
348executed.
349
350(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
351==>
352p = Popen(["somestring"], shell=True, bufsize=bufsize
353 stdin=PIPE, stdout=PIPE, close_fds=True)
354(child_stdout, child_stdin) = (p.stdout, p.stdin)
355
356
357(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
358==>
359p = Popen(["mycmd", "myarg"], bufsize=bufsize,
360 stdin=PIPE, stdout=PIPE, close_fds=True)
361(child_stdout, child_stdin) = (p.stdout, p.stdin)
362
363The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
364except that:
365
366* subprocess.Popen raises an exception if the execution fails
367* the capturestderr argument is replaced with the stderr argument.
368* stdin=PIPE and stdout=PIPE must be specified.
369* popen2 closes all filedescriptors by default, but you have to specify
Tim Peterse718f612004-10-12 21:51:32 +0000370 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371
372
373"""
374
375import sys
376mswindows = (sys.platform == "win32")
377
378import os
Peter Astrandc26516b2005-02-21 08:13:02 +0000379import types
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380import traceback
381
Peter Astrand454f7672005-01-01 09:36:35 +0000382# Exception classes used by this module.
383class CalledProcessError(OSError):
384 """This exception is raised when a process run by check_call() returns
385 a non-zero exit status. The exit status will be stored in the
386 errno attribute. This exception is a subclass of
387 OSError."""
388
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389if mswindows:
390 import threading
391 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000392 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000394 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
395 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
396 from win32api import GetCurrentProcess, DuplicateHandle, \
397 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000398 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000400 from win32process import CreateProcess, STARTUPINFO, \
401 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000402 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000404 else:
405 from _subprocess import *
406 class STARTUPINFO:
407 dwFlags = 0
408 hStdInput = None
409 hStdOutput = None
410 hStdError = None
411 class pywintypes:
412 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413else:
414 import select
415 import errno
416 import fcntl
417 import pickle
418
Peter Astrand454f7672005-01-01 09:36:35 +0000419__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420
421try:
422 MAXFD = os.sysconf("SC_OPEN_MAX")
423except:
424 MAXFD = 256
425
426# True/False does not exist on 2.2.0
427try:
428 False
429except NameError:
430 False = 0
431 True = 1
432
433_active = []
434
435def _cleanup():
436 for inst in _active[:]:
437 inst.poll()
438
439PIPE = -1
440STDOUT = -2
441
442
Peter Astrand5f5e1412004-12-05 20:15:36 +0000443def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 """Run command with arguments. Wait for command to complete, then
445 return the returncode attribute.
446
447 The arguments are the same as for the Popen constructor. Example:
448
449 retcode = call(["ls", "-l"])
450 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000451 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452
453
Peter Astrand454f7672005-01-01 09:36:35 +0000454def check_call(*popenargs, **kwargs):
455 """Run command with arguments. Wait for command to complete. If
456 the exit code was zero then return, otherwise raise
457 CalledProcessError. The CalledProcessError object will have the
458 return code in the errno attribute.
459
460 The arguments are the same as for the Popen constructor. Example:
461
462 check_call(["ls", "-l"])
463 """
464 retcode = call(*popenargs, **kwargs)
465 cmd = kwargs.get("args")
466 if cmd is None:
467 cmd = popenargs[0]
468 if retcode:
469 raise CalledProcessError(retcode, "Command %s returned non-zero exit status" % cmd)
470 return retcode
471
472
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000473def list2cmdline(seq):
474 """
475 Translate a sequence of arguments into a command line
476 string, using the same rules as the MS C runtime:
477
478 1) Arguments are delimited by white space, which is either a
479 space or a tab.
480
481 2) A string surrounded by double quotation marks is
482 interpreted as a single argument, regardless of white space
483 contained within. A quoted string can be embedded in an
484 argument.
485
486 3) A double quotation mark preceded by a backslash is
487 interpreted as a literal double quotation mark.
488
489 4) Backslashes are interpreted literally, unless they
490 immediately precede a double quotation mark.
491
492 5) If backslashes immediately precede a double quotation mark,
493 every pair of backslashes is interpreted as a literal
494 backslash. If the number of backslashes is odd, the last
495 backslash escapes the next double quotation mark as
496 described in rule 3.
497 """
498
499 # See
500 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
501 result = []
502 needquote = False
503 for arg in seq:
504 bs_buf = []
505
506 # Add a space to separate this argument from the others
507 if result:
508 result.append(' ')
509
510 needquote = (" " in arg) or ("\t" in arg)
511 if needquote:
512 result.append('"')
513
514 for c in arg:
515 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000516 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 bs_buf.append(c)
518 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000519 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 result.append('\\' * len(bs_buf)*2)
521 bs_buf = []
522 result.append('\\"')
523 else:
524 # Normal char
525 if bs_buf:
526 result.extend(bs_buf)
527 bs_buf = []
528 result.append(c)
529
Tim Peterse718f612004-10-12 21:51:32 +0000530 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 if bs_buf:
532 result.extend(bs_buf)
533
534 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000535 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 result.append('"')
537
538 return ''.join(result)
539
540
541class Popen(object):
542 def __init__(self, args, bufsize=0, executable=None,
543 stdin=None, stdout=None, stderr=None,
544 preexec_fn=None, close_fds=False, shell=False,
545 cwd=None, env=None, universal_newlines=False,
546 startupinfo=None, creationflags=0):
547 """Create new Popen instance."""
548 _cleanup()
549
Peter Astrand738131d2004-11-30 21:04:45 +0000550 if not isinstance(bufsize, (int, long)):
551 raise TypeError("bufsize must be an integer")
552
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000554 if preexec_fn is not None:
555 raise ValueError("preexec_fn is not supported on Windows "
556 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000558 raise ValueError("close_fds is not supported on Windows "
559 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560 else:
561 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000562 if startupinfo is not None:
563 raise ValueError("startupinfo is only supported on Windows "
564 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000566 raise ValueError("creationflags is only supported on Windows "
567 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568
Tim Peterse718f612004-10-12 21:51:32 +0000569 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 self.stdout = None
571 self.stderr = None
572 self.pid = None
573 self.returncode = None
574 self.universal_newlines = universal_newlines
575
576 # Input and output objects. The general principle is like
577 # this:
578 #
579 # Parent Child
580 # ------ -----
581 # p2cwrite ---stdin---> p2cread
582 # c2pread <--stdout--- c2pwrite
583 # errread <--stderr--- errwrite
584 #
585 # On POSIX, the child objects are file descriptors. On
586 # Windows, these are Windows file handles. The parent objects
587 # are file descriptors on both platforms. The parent objects
588 # are None when not using PIPEs. The child objects are None
589 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000590
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 (p2cread, p2cwrite,
592 c2pread, c2pwrite,
593 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
594
595 self._execute_child(args, executable, preexec_fn, close_fds,
596 cwd, env, universal_newlines,
597 startupinfo, creationflags, shell,
598 p2cread, p2cwrite,
599 c2pread, c2pwrite,
600 errread, errwrite)
601
602 if p2cwrite:
603 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
604 if c2pread:
605 if universal_newlines:
606 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
607 else:
608 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
609 if errread:
610 if universal_newlines:
611 self.stderr = os.fdopen(errread, 'rU', bufsize)
612 else:
613 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000614
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000615 _active.append(self)
616
617
618 def _translate_newlines(self, data):
619 data = data.replace("\r\n", "\n")
620 data = data.replace("\r", "\n")
621 return data
622
Peter Astrand23109f02005-03-03 20:28:59 +0000623 def communicate(self, input=None):
624 """Interact with process: Send data to stdin. Read data from
625 stdout and stderr, until end-of-file is reached. Wait for
626 process to terminate. The optional input argument should be a
627 string to be sent to the child process, or None, if no data
628 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000629
Peter Astrand23109f02005-03-03 20:28:59 +0000630 communicate() returns a tuple (stdout, stderr)."""
631
632 # Optimization: If we are only using one pipe, or no pipe at
633 # all, using select() or threads is unnecessary.
634 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000635 stdout = None
636 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000637 if self.stdin:
638 if input:
639 self.stdin.write(input)
640 self.stdin.close()
641 elif self.stdout:
642 stdout = self.stdout.read()
643 elif self.stderr:
644 stderr = self.stderr.read()
645 self.wait()
646 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000647
Peter Astrand23109f02005-03-03 20:28:59 +0000648 return self._communicate(input)
649
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650
651 if mswindows:
652 #
653 # Windows methods
654 #
655 def _get_handles(self, stdin, stdout, stderr):
656 """Construct and return tupel with IO objects:
657 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
658 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000659 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000661
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 p2cread, p2cwrite = None, None
663 c2pread, c2pwrite = None, None
664 errread, errwrite = None, None
665
Peter Astrandd38ddf42005-02-10 08:32:50 +0000666 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 p2cread = GetStdHandle(STD_INPUT_HANDLE)
668 elif stdin == PIPE:
669 p2cread, p2cwrite = CreatePipe(None, 0)
670 # Detach and turn into fd
671 p2cwrite = p2cwrite.Detach()
672 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000673 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674 p2cread = msvcrt.get_osfhandle(stdin)
675 else:
676 # Assuming file-like object
677 p2cread = msvcrt.get_osfhandle(stdin.fileno())
678 p2cread = self._make_inheritable(p2cread)
679
Peter Astrandd38ddf42005-02-10 08:32:50 +0000680 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
682 elif stdout == PIPE:
683 c2pread, c2pwrite = CreatePipe(None, 0)
684 # Detach and turn into fd
685 c2pread = c2pread.Detach()
686 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000687 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000688 c2pwrite = msvcrt.get_osfhandle(stdout)
689 else:
690 # Assuming file-like object
691 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
692 c2pwrite = self._make_inheritable(c2pwrite)
693
Peter Astrandd38ddf42005-02-10 08:32:50 +0000694 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000695 errwrite = GetStdHandle(STD_ERROR_HANDLE)
696 elif stderr == PIPE:
697 errread, errwrite = CreatePipe(None, 0)
698 # Detach and turn into fd
699 errread = errread.Detach()
700 errread = msvcrt.open_osfhandle(errread, 0)
701 elif stderr == STDOUT:
702 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000703 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704 errwrite = msvcrt.get_osfhandle(stderr)
705 else:
706 # Assuming file-like object
707 errwrite = msvcrt.get_osfhandle(stderr.fileno())
708 errwrite = self._make_inheritable(errwrite)
709
710 return (p2cread, p2cwrite,
711 c2pread, c2pwrite,
712 errread, errwrite)
713
714
715 def _make_inheritable(self, handle):
716 """Return a duplicate of handle, which is inheritable"""
717 return DuplicateHandle(GetCurrentProcess(), handle,
718 GetCurrentProcess(), 0, 1,
719 DUPLICATE_SAME_ACCESS)
720
721
722 def _find_w9xpopen(self):
723 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000724 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
725 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 if not os.path.exists(w9xpopen):
727 # Eeek - file-not-found - possibly an embedding
728 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000729 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
730 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000732 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
733 "needed for Popen to work with your "
734 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735 return w9xpopen
736
Tim Peterse718f612004-10-12 21:51:32 +0000737
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 def _execute_child(self, args, executable, preexec_fn, close_fds,
739 cwd, env, universal_newlines,
740 startupinfo, creationflags, shell,
741 p2cread, p2cwrite,
742 c2pread, c2pwrite,
743 errread, errwrite):
744 """Execute program (MS Windows version)"""
745
Peter Astrandc26516b2005-02-21 08:13:02 +0000746 if not isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 args = list2cmdline(args)
748
Peter Astrandc1d65362004-11-07 14:30:34 +0000749 # Process startup details
750 default_startupinfo = STARTUPINFO()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000751 if startupinfo is None:
Peter Astrandc1d65362004-11-07 14:30:34 +0000752 startupinfo = default_startupinfo
753 if not None in (p2cread, c2pwrite, errwrite):
754 startupinfo.dwFlags |= STARTF_USESTDHANDLES
755 startupinfo.hStdInput = p2cread
756 startupinfo.hStdOutput = c2pwrite
757 startupinfo.hStdError = errwrite
758
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000760 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
761 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 comspec = os.environ.get("COMSPEC", "cmd.exe")
763 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000764 if (GetVersion() >= 0x80000000L or
765 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 # Win9x, or using command.com on NT. We need to
767 # use the w9xpopen intermediate program. For more
768 # information, see KB Q150956
769 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
770 w9xpopen = self._find_w9xpopen()
771 args = '"%s" %s' % (w9xpopen, args)
772 # Not passing CREATE_NEW_CONSOLE has been known to
773 # cause random failures on win9x. Specifically a
774 # dialog: "Your program accessed mem currently in
775 # use at xxx" and a hopeful warning about the
776 # stability of your system. Cost is Ctrl+C wont
777 # kill children.
778 creationflags |= CREATE_NEW_CONSOLE
779
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 # Start the process
781 try:
782 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000783 # no special security
784 None, None,
785 # must inherit handles to pass std
786 # handles
787 1,
788 creationflags,
789 env,
790 cwd,
791 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 except pywintypes.error, e:
793 # Translate pywintypes.error to WindowsError, which is
794 # a subclass of OSError. FIXME: We should really
795 # translate errno using _sys_errlist (or simliar), but
796 # how can this be done from Python?
797 raise WindowsError(*e.args)
798
799 # Retain the process handle, but close the thread handle
800 self._handle = hp
801 self.pid = pid
802 ht.Close()
803
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000804 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 # handles that only the child should have open. You need
806 # to make sure that no handles to the write end of the
807 # output pipe are maintained in this process or else the
808 # pipe will not close when the child process exits and the
809 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000810 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000812 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000814 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 errwrite.Close()
816
Tim Peterse718f612004-10-12 21:51:32 +0000817
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000818 def poll(self):
819 """Check if child process has terminated. Returns returncode
820 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000821 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000822 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
823 self.returncode = GetExitCodeProcess(self._handle)
824 _active.remove(self)
825 return self.returncode
826
827
828 def wait(self):
829 """Wait for child process to terminate. Returns returncode
830 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000831 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 obj = WaitForSingleObject(self._handle, INFINITE)
833 self.returncode = GetExitCodeProcess(self._handle)
834 _active.remove(self)
835 return self.returncode
836
837
838 def _readerthread(self, fh, buffer):
839 buffer.append(fh.read())
840
841
Peter Astrand23109f02005-03-03 20:28:59 +0000842 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 stdout = None # Return
844 stderr = None # Return
845
846 if self.stdout:
847 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000848 stdout_thread = threading.Thread(target=self._readerthread,
849 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 stdout_thread.setDaemon(True)
851 stdout_thread.start()
852 if self.stderr:
853 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000854 stderr_thread = threading.Thread(target=self._readerthread,
855 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856 stderr_thread.setDaemon(True)
857 stderr_thread.start()
858
859 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000860 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861 self.stdin.write(input)
862 self.stdin.close()
863
864 if self.stdout:
865 stdout_thread.join()
866 if self.stderr:
867 stderr_thread.join()
868
869 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000870 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000872 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 stderr = stderr[0]
874
875 # Translate newlines, if requested. We cannot let the file
876 # object do the translation: It is based on stdio, which is
877 # impossible to combine with select (unless forcing no
878 # buffering).
879 if self.universal_newlines and hasattr(open, 'newlines'):
880 if stdout:
881 stdout = self._translate_newlines(stdout)
882 if stderr:
883 stderr = self._translate_newlines(stderr)
884
885 self.wait()
886 return (stdout, stderr)
887
888 else:
889 #
890 # POSIX methods
891 #
892 def _get_handles(self, stdin, stdout, stderr):
893 """Construct and return tupel with IO objects:
894 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
895 """
896 p2cread, p2cwrite = None, None
897 c2pread, c2pwrite = None, None
898 errread, errwrite = None, None
899
Peter Astrandd38ddf42005-02-10 08:32:50 +0000900 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000901 pass
902 elif stdin == PIPE:
903 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000904 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000905 p2cread = stdin
906 else:
907 # Assuming file-like object
908 p2cread = stdin.fileno()
909
Peter Astrandd38ddf42005-02-10 08:32:50 +0000910 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 pass
912 elif stdout == PIPE:
913 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000914 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 c2pwrite = stdout
916 else:
917 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000918 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
Peter Astrandd38ddf42005-02-10 08:32:50 +0000920 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921 pass
922 elif stderr == PIPE:
923 errread, errwrite = os.pipe()
924 elif stderr == STDOUT:
925 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000926 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927 errwrite = stderr
928 else:
929 # Assuming file-like object
930 errwrite = stderr.fileno()
931
932 return (p2cread, p2cwrite,
933 c2pread, c2pwrite,
934 errread, errwrite)
935
936
937 def _set_cloexec_flag(self, fd):
938 try:
939 cloexec_flag = fcntl.FD_CLOEXEC
940 except AttributeError:
941 cloexec_flag = 1
942
943 old = fcntl.fcntl(fd, fcntl.F_GETFD)
944 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
945
946
947 def _close_fds(self, but):
948 for i in range(3, MAXFD):
949 if i == but:
950 continue
951 try:
952 os.close(i)
953 except:
954 pass
Tim Peterse718f612004-10-12 21:51:32 +0000955
956
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 def _execute_child(self, args, executable, preexec_fn, close_fds,
958 cwd, env, universal_newlines,
959 startupinfo, creationflags, shell,
960 p2cread, p2cwrite,
961 c2pread, c2pwrite,
962 errread, errwrite):
963 """Execute program (POSIX version)"""
964
Peter Astrandc26516b2005-02-21 08:13:02 +0000965 if isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966 args = [args]
967
968 if shell:
969 args = ["/bin/sh", "-c"] + args
970
Peter Astrandd38ddf42005-02-10 08:32:50 +0000971 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000972 executable = args[0]
973
974 # For transferring possible exec failure from child to parent
975 # The first char specifies the exception type: 0 means
976 # OSError, 1 means some other error.
977 errpipe_read, errpipe_write = os.pipe()
978 self._set_cloexec_flag(errpipe_write)
979
980 self.pid = os.fork()
981 if self.pid == 0:
982 # Child
983 try:
984 # Close parent's pipe ends
985 if p2cwrite:
986 os.close(p2cwrite)
987 if c2pread:
988 os.close(c2pread)
989 if errread:
990 os.close(errread)
991 os.close(errpipe_read)
992
993 # Dup fds for child
994 if p2cread:
995 os.dup2(p2cread, 0)
996 if c2pwrite:
997 os.dup2(c2pwrite, 1)
998 if errwrite:
999 os.dup2(errwrite, 2)
1000
1001 # Close pipe fds. Make sure we doesn't close the same
1002 # fd more than once.
1003 if p2cread:
1004 os.close(p2cread)
1005 if c2pwrite and c2pwrite not in (p2cread,):
1006 os.close(c2pwrite)
1007 if errwrite and errwrite not in (p2cread, c2pwrite):
1008 os.close(errwrite)
1009
1010 # Close all other fds, if asked for
1011 if close_fds:
1012 self._close_fds(but=errpipe_write)
1013
Peter Astrandd38ddf42005-02-10 08:32:50 +00001014 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001015 os.chdir(cwd)
1016
1017 if preexec_fn:
1018 apply(preexec_fn)
1019
Peter Astrandd38ddf42005-02-10 08:32:50 +00001020 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001021 os.execvp(executable, args)
1022 else:
1023 os.execvpe(executable, args, env)
1024
1025 except:
1026 exc_type, exc_value, tb = sys.exc_info()
1027 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001028 exc_lines = traceback.format_exception(exc_type,
1029 exc_value,
1030 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031 exc_value.child_traceback = ''.join(exc_lines)
1032 os.write(errpipe_write, pickle.dumps(exc_value))
1033
1034 # This exitcode won't be reported to applications, so it
1035 # really doesn't matter what we return.
1036 os._exit(255)
1037
1038 # Parent
1039 os.close(errpipe_write)
1040 if p2cread and p2cwrite:
1041 os.close(p2cread)
1042 if c2pwrite and c2pread:
1043 os.close(c2pwrite)
1044 if errwrite and errread:
1045 os.close(errwrite)
1046
1047 # Wait for exec to fail or succeed; possibly raising exception
1048 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1049 os.close(errpipe_read)
1050 if data != "":
Peter Astrandf791d7a2005-01-01 09:38:57 +00001051 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001052 child_exception = pickle.loads(data)
1053 raise child_exception
1054
1055
1056 def _handle_exitstatus(self, sts):
1057 if os.WIFSIGNALED(sts):
1058 self.returncode = -os.WTERMSIG(sts)
1059 elif os.WIFEXITED(sts):
1060 self.returncode = os.WEXITSTATUS(sts)
1061 else:
1062 # Should never happen
1063 raise RuntimeError("Unknown child exit status!")
1064
1065 _active.remove(self)
1066
Tim Peterse718f612004-10-12 21:51:32 +00001067
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068 def poll(self):
1069 """Check if child process has terminated. Returns returncode
1070 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001071 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 try:
1073 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1074 if pid == self.pid:
1075 self._handle_exitstatus(sts)
1076 except os.error:
1077 pass
1078 return self.returncode
1079
1080
1081 def wait(self):
1082 """Wait for child process to terminate. Returns returncode
1083 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001084 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 pid, sts = os.waitpid(self.pid, 0)
1086 self._handle_exitstatus(sts)
1087 return self.returncode
1088
1089
Peter Astrand23109f02005-03-03 20:28:59 +00001090 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091 read_set = []
1092 write_set = []
1093 stdout = None # Return
1094 stderr = None # Return
1095
1096 if self.stdin:
1097 # Flush stdio buffer. This might block, if the user has
1098 # been writing to .stdin in an uncontrolled fashion.
1099 self.stdin.flush()
1100 if input:
1101 write_set.append(self.stdin)
1102 else:
1103 self.stdin.close()
1104 if self.stdout:
1105 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001106 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001107 if self.stderr:
1108 read_set.append(self.stderr)
1109 stderr = []
1110
1111 while read_set or write_set:
1112 rlist, wlist, xlist = select.select(read_set, write_set, [])
1113
1114 if self.stdin in wlist:
1115 # When select has indicated that the file is writable,
1116 # we can write up to PIPE_BUF bytes without risk
1117 # blocking. POSIX defines PIPE_BUF >= 512
1118 bytes_written = os.write(self.stdin.fileno(), input[:512])
1119 input = input[bytes_written:]
1120 if not input:
1121 self.stdin.close()
1122 write_set.remove(self.stdin)
1123
1124 if self.stdout in rlist:
1125 data = os.read(self.stdout.fileno(), 1024)
1126 if data == "":
1127 self.stdout.close()
1128 read_set.remove(self.stdout)
1129 stdout.append(data)
1130
1131 if self.stderr in rlist:
1132 data = os.read(self.stderr.fileno(), 1024)
1133 if data == "":
1134 self.stderr.close()
1135 read_set.remove(self.stderr)
1136 stderr.append(data)
1137
1138 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001139 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140 stdout = ''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001141 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001142 stderr = ''.join(stderr)
1143
1144 # Translate newlines, if requested. We cannot let the file
1145 # object do the translation: It is based on stdio, which is
1146 # impossible to combine with select (unless forcing no
1147 # buffering).
1148 if self.universal_newlines and hasattr(open, 'newlines'):
1149 if stdout:
1150 stdout = self._translate_newlines(stdout)
1151 if stderr:
1152 stderr = self._translate_newlines(stderr)
1153
1154 self.wait()
1155 return (stdout, stderr)
1156
1157
1158def _demo_posix():
1159 #
1160 # Example 1: Simple redirection: Get process list
1161 #
1162 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1163 print "Process list:"
1164 print plist
1165
1166 #
1167 # Example 2: Change uid before executing child
1168 #
1169 if os.getuid() == 0:
1170 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1171 p.wait()
1172
1173 #
1174 # Example 3: Connecting several subprocesses
1175 #
1176 print "Looking for 'hda'..."
1177 p1 = Popen(["dmesg"], stdout=PIPE)
1178 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1179 print repr(p2.communicate()[0])
1180
1181 #
1182 # Example 4: Catch execution error
1183 #
1184 print
1185 print "Trying a weird file..."
1186 try:
1187 print Popen(["/this/path/does/not/exist"]).communicate()
1188 except OSError, e:
1189 if e.errno == errno.ENOENT:
1190 print "The file didn't exist. I thought so..."
1191 print "Child traceback:"
1192 print e.child_traceback
1193 else:
1194 print "Error", e.errno
1195 else:
1196 print >>sys.stderr, "Gosh. No error."
1197
1198
1199def _demo_windows():
1200 #
1201 # Example 1: Connecting several subprocesses
1202 #
1203 print "Looking for 'PROMPT' in set output..."
1204 p1 = Popen("set", stdout=PIPE, shell=True)
1205 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1206 print repr(p2.communicate()[0])
1207
1208 #
1209 # Example 2: Simple execution of program
1210 #
1211 print "Executing calc..."
1212 p = Popen("calc")
1213 p.wait()
1214
1215
1216if __name__ == "__main__":
1217 if mswindows:
1218 _demo_windows()
1219 else:
1220 _demo_posix()