blob: 61effde7b6dee9843943358736f7dcd3a190bac8 [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:
535 result.append('"')
536
537 return ''.join(result)
538
539
540class Popen(object):
541 def __init__(self, args, bufsize=0, executable=None,
542 stdin=None, stdout=None, stderr=None,
543 preexec_fn=None, close_fds=False, shell=False,
544 cwd=None, env=None, universal_newlines=False,
545 startupinfo=None, creationflags=0):
546 """Create new Popen instance."""
547 _cleanup()
548
Peter Astrand738131d2004-11-30 21:04:45 +0000549 if not isinstance(bufsize, (int, long)):
550 raise TypeError("bufsize must be an integer")
551
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000553 if preexec_fn is not None:
554 raise ValueError("preexec_fn is not supported on Windows "
555 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000557 raise ValueError("close_fds is not supported on Windows "
558 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 else:
560 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000561 if startupinfo is not None:
562 raise ValueError("startupinfo is only supported on Windows "
563 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000565 raise ValueError("creationflags is only supported on Windows "
566 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567
Tim Peterse718f612004-10-12 21:51:32 +0000568 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000569 self.stdout = None
570 self.stderr = None
571 self.pid = None
572 self.returncode = None
573 self.universal_newlines = universal_newlines
574
575 # Input and output objects. The general principle is like
576 # this:
577 #
578 # Parent Child
579 # ------ -----
580 # p2cwrite ---stdin---> p2cread
581 # c2pread <--stdout--- c2pwrite
582 # errread <--stderr--- errwrite
583 #
584 # On POSIX, the child objects are file descriptors. On
585 # Windows, these are Windows file handles. The parent objects
586 # are file descriptors on both platforms. The parent objects
587 # are None when not using PIPEs. The child objects are None
588 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000589
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 (p2cread, p2cwrite,
591 c2pread, c2pwrite,
592 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
593
594 self._execute_child(args, executable, preexec_fn, close_fds,
595 cwd, env, universal_newlines,
596 startupinfo, creationflags, shell,
597 p2cread, p2cwrite,
598 c2pread, c2pwrite,
599 errread, errwrite)
600
601 if p2cwrite:
602 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
603 if c2pread:
604 if universal_newlines:
605 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
606 else:
607 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
608 if errread:
609 if universal_newlines:
610 self.stderr = os.fdopen(errread, 'rU', bufsize)
611 else:
612 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000613
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 _active.append(self)
615
616
617 def _translate_newlines(self, data):
618 data = data.replace("\r\n", "\n")
619 data = data.replace("\r", "\n")
620 return data
621
Peter Astrand23109f02005-03-03 20:28:59 +0000622 def communicate(self, input=None):
623 """Interact with process: Send data to stdin. Read data from
624 stdout and stderr, until end-of-file is reached. Wait for
625 process to terminate. The optional input argument should be a
626 string to be sent to the child process, or None, if no data
627 should be sent to the child.
628
629 communicate() returns a tuple (stdout, stderr)."""
630
631 # Optimization: If we are only using one pipe, or no pipe at
632 # all, using select() or threads is unnecessary.
633 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
634 stdout = None
635 stderr = None
636 if self.stdin:
637 if input:
638 self.stdin.write(input)
639 self.stdin.close()
640 elif self.stdout:
641 stdout = self.stdout.read()
642 elif self.stderr:
643 stderr = self.stderr.read()
644 self.wait()
645 return (stdout, stderr)
646
647 return self._communicate(input)
648
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000649
650 if mswindows:
651 #
652 # Windows methods
653 #
654 def _get_handles(self, stdin, stdout, stderr):
655 """Construct and return tupel with IO objects:
656 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
657 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000658 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000660
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 p2cread, p2cwrite = None, None
662 c2pread, c2pwrite = None, None
663 errread, errwrite = None, None
664
Peter Astrandd38ddf42005-02-10 08:32:50 +0000665 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 p2cread = GetStdHandle(STD_INPUT_HANDLE)
667 elif stdin == PIPE:
668 p2cread, p2cwrite = CreatePipe(None, 0)
669 # Detach and turn into fd
670 p2cwrite = p2cwrite.Detach()
671 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000672 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673 p2cread = msvcrt.get_osfhandle(stdin)
674 else:
675 # Assuming file-like object
676 p2cread = msvcrt.get_osfhandle(stdin.fileno())
677 p2cread = self._make_inheritable(p2cread)
678
Peter Astrandd38ddf42005-02-10 08:32:50 +0000679 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
681 elif stdout == PIPE:
682 c2pread, c2pwrite = CreatePipe(None, 0)
683 # Detach and turn into fd
684 c2pread = c2pread.Detach()
685 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000686 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 c2pwrite = msvcrt.get_osfhandle(stdout)
688 else:
689 # Assuming file-like object
690 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
691 c2pwrite = self._make_inheritable(c2pwrite)
692
Peter Astrandd38ddf42005-02-10 08:32:50 +0000693 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 errwrite = GetStdHandle(STD_ERROR_HANDLE)
695 elif stderr == PIPE:
696 errread, errwrite = CreatePipe(None, 0)
697 # Detach and turn into fd
698 errread = errread.Detach()
699 errread = msvcrt.open_osfhandle(errread, 0)
700 elif stderr == STDOUT:
701 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000702 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 errwrite = msvcrt.get_osfhandle(stderr)
704 else:
705 # Assuming file-like object
706 errwrite = msvcrt.get_osfhandle(stderr.fileno())
707 errwrite = self._make_inheritable(errwrite)
708
709 return (p2cread, p2cwrite,
710 c2pread, c2pwrite,
711 errread, errwrite)
712
713
714 def _make_inheritable(self, handle):
715 """Return a duplicate of handle, which is inheritable"""
716 return DuplicateHandle(GetCurrentProcess(), handle,
717 GetCurrentProcess(), 0, 1,
718 DUPLICATE_SAME_ACCESS)
719
720
721 def _find_w9xpopen(self):
722 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000723 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
724 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725 if not os.path.exists(w9xpopen):
726 # Eeek - file-not-found - possibly an embedding
727 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000728 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
729 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000731 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
732 "needed for Popen to work with your "
733 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 return w9xpopen
735
Tim Peterse718f612004-10-12 21:51:32 +0000736
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737 def _execute_child(self, args, executable, preexec_fn, close_fds,
738 cwd, env, universal_newlines,
739 startupinfo, creationflags, shell,
740 p2cread, p2cwrite,
741 c2pread, c2pwrite,
742 errread, errwrite):
743 """Execute program (MS Windows version)"""
744
Peter Astrandc26516b2005-02-21 08:13:02 +0000745 if not isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 args = list2cmdline(args)
747
Peter Astrandc1d65362004-11-07 14:30:34 +0000748 # Process startup details
749 default_startupinfo = STARTUPINFO()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000750 if startupinfo is None:
Peter Astrandc1d65362004-11-07 14:30:34 +0000751 startupinfo = default_startupinfo
752 if not None in (p2cread, c2pwrite, errwrite):
753 startupinfo.dwFlags |= STARTF_USESTDHANDLES
754 startupinfo.hStdInput = p2cread
755 startupinfo.hStdOutput = c2pwrite
756 startupinfo.hStdError = errwrite
757
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000759 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
760 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 comspec = os.environ.get("COMSPEC", "cmd.exe")
762 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000763 if (GetVersion() >= 0x80000000L or
764 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000765 # Win9x, or using command.com on NT. We need to
766 # use the w9xpopen intermediate program. For more
767 # information, see KB Q150956
768 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
769 w9xpopen = self._find_w9xpopen()
770 args = '"%s" %s' % (w9xpopen, args)
771 # Not passing CREATE_NEW_CONSOLE has been known to
772 # cause random failures on win9x. Specifically a
773 # dialog: "Your program accessed mem currently in
774 # use at xxx" and a hopeful warning about the
775 # stability of your system. Cost is Ctrl+C wont
776 # kill children.
777 creationflags |= CREATE_NEW_CONSOLE
778
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779 # Start the process
780 try:
781 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000782 # no special security
783 None, None,
784 # must inherit handles to pass std
785 # handles
786 1,
787 creationflags,
788 env,
789 cwd,
790 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 except pywintypes.error, e:
792 # Translate pywintypes.error to WindowsError, which is
793 # a subclass of OSError. FIXME: We should really
794 # translate errno using _sys_errlist (or simliar), but
795 # how can this be done from Python?
796 raise WindowsError(*e.args)
797
798 # Retain the process handle, but close the thread handle
799 self._handle = hp
800 self.pid = pid
801 ht.Close()
802
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000803 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 # handles that only the child should have open. You need
805 # to make sure that no handles to the write end of the
806 # output pipe are maintained in this process or else the
807 # pipe will not close when the child process exits and the
808 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000809 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000810 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000811 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000812 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000813 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 errwrite.Close()
815
Tim Peterse718f612004-10-12 21:51:32 +0000816
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 def poll(self):
818 """Check if child process has terminated. Returns returncode
819 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000820 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000821 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
822 self.returncode = GetExitCodeProcess(self._handle)
823 _active.remove(self)
824 return self.returncode
825
826
827 def wait(self):
828 """Wait for child process to terminate. Returns returncode
829 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000830 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 obj = WaitForSingleObject(self._handle, INFINITE)
832 self.returncode = GetExitCodeProcess(self._handle)
833 _active.remove(self)
834 return self.returncode
835
836
837 def _readerthread(self, fh, buffer):
838 buffer.append(fh.read())
839
840
Peter Astrand23109f02005-03-03 20:28:59 +0000841 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 stdout = None # Return
843 stderr = None # Return
844
845 if self.stdout:
846 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000847 stdout_thread = threading.Thread(target=self._readerthread,
848 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 stdout_thread.setDaemon(True)
850 stdout_thread.start()
851 if self.stderr:
852 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000853 stderr_thread = threading.Thread(target=self._readerthread,
854 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 stderr_thread.setDaemon(True)
856 stderr_thread.start()
857
858 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000859 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860 self.stdin.write(input)
861 self.stdin.close()
862
863 if self.stdout:
864 stdout_thread.join()
865 if self.stderr:
866 stderr_thread.join()
867
868 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000869 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000871 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 stderr = stderr[0]
873
874 # Translate newlines, if requested. We cannot let the file
875 # object do the translation: It is based on stdio, which is
876 # impossible to combine with select (unless forcing no
877 # buffering).
878 if self.universal_newlines and hasattr(open, 'newlines'):
879 if stdout:
880 stdout = self._translate_newlines(stdout)
881 if stderr:
882 stderr = self._translate_newlines(stderr)
883
884 self.wait()
885 return (stdout, stderr)
886
887 else:
888 #
889 # POSIX methods
890 #
891 def _get_handles(self, stdin, stdout, stderr):
892 """Construct and return tupel with IO objects:
893 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
894 """
895 p2cread, p2cwrite = None, None
896 c2pread, c2pwrite = None, None
897 errread, errwrite = None, None
898
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 pass
901 elif stdin == PIPE:
902 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000903 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904 p2cread = stdin
905 else:
906 # Assuming file-like object
907 p2cread = stdin.fileno()
908
Peter Astrandd38ddf42005-02-10 08:32:50 +0000909 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910 pass
911 elif stdout == PIPE:
912 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000913 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914 c2pwrite = stdout
915 else:
916 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000917 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000918
Peter Astrandd38ddf42005-02-10 08:32:50 +0000919 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 pass
921 elif stderr == PIPE:
922 errread, errwrite = os.pipe()
923 elif stderr == STDOUT:
924 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000925 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926 errwrite = stderr
927 else:
928 # Assuming file-like object
929 errwrite = stderr.fileno()
930
931 return (p2cread, p2cwrite,
932 c2pread, c2pwrite,
933 errread, errwrite)
934
935
936 def _set_cloexec_flag(self, fd):
937 try:
938 cloexec_flag = fcntl.FD_CLOEXEC
939 except AttributeError:
940 cloexec_flag = 1
941
942 old = fcntl.fcntl(fd, fcntl.F_GETFD)
943 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
944
945
946 def _close_fds(self, but):
947 for i in range(3, MAXFD):
948 if i == but:
949 continue
950 try:
951 os.close(i)
952 except:
953 pass
Tim Peterse718f612004-10-12 21:51:32 +0000954
955
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000956 def _execute_child(self, args, executable, preexec_fn, close_fds,
957 cwd, env, universal_newlines,
958 startupinfo, creationflags, shell,
959 p2cread, p2cwrite,
960 c2pread, c2pwrite,
961 errread, errwrite):
962 """Execute program (POSIX version)"""
963
Peter Astrandc26516b2005-02-21 08:13:02 +0000964 if isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965 args = [args]
966
967 if shell:
968 args = ["/bin/sh", "-c"] + args
969
Peter Astrandd38ddf42005-02-10 08:32:50 +0000970 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971 executable = args[0]
972
973 # For transferring possible exec failure from child to parent
974 # The first char specifies the exception type: 0 means
975 # OSError, 1 means some other error.
976 errpipe_read, errpipe_write = os.pipe()
977 self._set_cloexec_flag(errpipe_write)
978
979 self.pid = os.fork()
980 if self.pid == 0:
981 # Child
982 try:
983 # Close parent's pipe ends
984 if p2cwrite:
985 os.close(p2cwrite)
986 if c2pread:
987 os.close(c2pread)
988 if errread:
989 os.close(errread)
990 os.close(errpipe_read)
991
992 # Dup fds for child
993 if p2cread:
994 os.dup2(p2cread, 0)
995 if c2pwrite:
996 os.dup2(c2pwrite, 1)
997 if errwrite:
998 os.dup2(errwrite, 2)
999
1000 # Close pipe fds. Make sure we doesn't close the same
1001 # fd more than once.
1002 if p2cread:
1003 os.close(p2cread)
1004 if c2pwrite and c2pwrite not in (p2cread,):
1005 os.close(c2pwrite)
1006 if errwrite and errwrite not in (p2cread, c2pwrite):
1007 os.close(errwrite)
1008
1009 # Close all other fds, if asked for
1010 if close_fds:
1011 self._close_fds(but=errpipe_write)
1012
Peter Astrandd38ddf42005-02-10 08:32:50 +00001013 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014 os.chdir(cwd)
1015
1016 if preexec_fn:
1017 apply(preexec_fn)
1018
Peter Astrandd38ddf42005-02-10 08:32:50 +00001019 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 os.execvp(executable, args)
1021 else:
1022 os.execvpe(executable, args, env)
1023
1024 except:
1025 exc_type, exc_value, tb = sys.exc_info()
1026 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001027 exc_lines = traceback.format_exception(exc_type,
1028 exc_value,
1029 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 exc_value.child_traceback = ''.join(exc_lines)
1031 os.write(errpipe_write, pickle.dumps(exc_value))
1032
1033 # This exitcode won't be reported to applications, so it
1034 # really doesn't matter what we return.
1035 os._exit(255)
1036
1037 # Parent
1038 os.close(errpipe_write)
1039 if p2cread and p2cwrite:
1040 os.close(p2cread)
1041 if c2pwrite and c2pread:
1042 os.close(c2pwrite)
1043 if errwrite and errread:
1044 os.close(errwrite)
1045
1046 # Wait for exec to fail or succeed; possibly raising exception
1047 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1048 os.close(errpipe_read)
1049 if data != "":
Peter Astrandf791d7a2005-01-01 09:38:57 +00001050 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051 child_exception = pickle.loads(data)
1052 raise child_exception
1053
1054
1055 def _handle_exitstatus(self, sts):
1056 if os.WIFSIGNALED(sts):
1057 self.returncode = -os.WTERMSIG(sts)
1058 elif os.WIFEXITED(sts):
1059 self.returncode = os.WEXITSTATUS(sts)
1060 else:
1061 # Should never happen
1062 raise RuntimeError("Unknown child exit status!")
1063
1064 _active.remove(self)
1065
Tim Peterse718f612004-10-12 21:51:32 +00001066
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067 def poll(self):
1068 """Check if child process has terminated. Returns returncode
1069 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001070 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071 try:
1072 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1073 if pid == self.pid:
1074 self._handle_exitstatus(sts)
1075 except os.error:
1076 pass
1077 return self.returncode
1078
1079
1080 def wait(self):
1081 """Wait for child process to terminate. Returns returncode
1082 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001083 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001084 pid, sts = os.waitpid(self.pid, 0)
1085 self._handle_exitstatus(sts)
1086 return self.returncode
1087
1088
Peter Astrand23109f02005-03-03 20:28:59 +00001089 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 read_set = []
1091 write_set = []
1092 stdout = None # Return
1093 stderr = None # Return
1094
1095 if self.stdin:
1096 # Flush stdio buffer. This might block, if the user has
1097 # been writing to .stdin in an uncontrolled fashion.
1098 self.stdin.flush()
1099 if input:
1100 write_set.append(self.stdin)
1101 else:
1102 self.stdin.close()
1103 if self.stdout:
1104 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001105 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106 if self.stderr:
1107 read_set.append(self.stderr)
1108 stderr = []
1109
1110 while read_set or write_set:
1111 rlist, wlist, xlist = select.select(read_set, write_set, [])
1112
1113 if self.stdin in wlist:
1114 # When select has indicated that the file is writable,
1115 # we can write up to PIPE_BUF bytes without risk
1116 # blocking. POSIX defines PIPE_BUF >= 512
1117 bytes_written = os.write(self.stdin.fileno(), input[:512])
1118 input = input[bytes_written:]
1119 if not input:
1120 self.stdin.close()
1121 write_set.remove(self.stdin)
1122
1123 if self.stdout in rlist:
1124 data = os.read(self.stdout.fileno(), 1024)
1125 if data == "":
1126 self.stdout.close()
1127 read_set.remove(self.stdout)
1128 stdout.append(data)
1129
1130 if self.stderr in rlist:
1131 data = os.read(self.stderr.fileno(), 1024)
1132 if data == "":
1133 self.stderr.close()
1134 read_set.remove(self.stderr)
1135 stderr.append(data)
1136
1137 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001138 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001139 stdout = ''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001140 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001141 stderr = ''.join(stderr)
1142
1143 # Translate newlines, if requested. We cannot let the file
1144 # object do the translation: It is based on stdio, which is
1145 # impossible to combine with select (unless forcing no
1146 # buffering).
1147 if self.universal_newlines and hasattr(open, 'newlines'):
1148 if stdout:
1149 stdout = self._translate_newlines(stdout)
1150 if stderr:
1151 stderr = self._translate_newlines(stderr)
1152
1153 self.wait()
1154 return (stdout, stderr)
1155
1156
1157def _demo_posix():
1158 #
1159 # Example 1: Simple redirection: Get process list
1160 #
1161 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1162 print "Process list:"
1163 print plist
1164
1165 #
1166 # Example 2: Change uid before executing child
1167 #
1168 if os.getuid() == 0:
1169 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1170 p.wait()
1171
1172 #
1173 # Example 3: Connecting several subprocesses
1174 #
1175 print "Looking for 'hda'..."
1176 p1 = Popen(["dmesg"], stdout=PIPE)
1177 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1178 print repr(p2.communicate()[0])
1179
1180 #
1181 # Example 4: Catch execution error
1182 #
1183 print
1184 print "Trying a weird file..."
1185 try:
1186 print Popen(["/this/path/does/not/exist"]).communicate()
1187 except OSError, e:
1188 if e.errno == errno.ENOENT:
1189 print "The file didn't exist. I thought so..."
1190 print "Child traceback:"
1191 print e.child_traceback
1192 else:
1193 print "Error", e.errno
1194 else:
1195 print >>sys.stderr, "Gosh. No error."
1196
1197
1198def _demo_windows():
1199 #
1200 # Example 1: Connecting several subprocesses
1201 #
1202 print "Looking for 'PROMPT' in set output..."
1203 p1 = Popen("set", stdout=PIPE, shell=True)
1204 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1205 print repr(p2.communicate()[0])
1206
1207 #
1208 # Example 2: Simple execution of program
1209 #
1210 print "Executing calc..."
1211 p = Popen("calc")
1212 p.wait()
1213
1214
1215if __name__ == "__main__":
1216 if mswindows:
1217 _demo_windows()
1218 else:
1219 _demo_posix()