blob: 382acb6927a4f3842364c365e863875c9803bbaf [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
622
623 if mswindows:
624 #
625 # Windows methods
626 #
627 def _get_handles(self, stdin, stdout, stderr):
628 """Construct and return tupel with IO objects:
629 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
630 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000631 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000633
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 p2cread, p2cwrite = None, None
635 c2pread, c2pwrite = None, None
636 errread, errwrite = None, None
637
Peter Astrandd38ddf42005-02-10 08:32:50 +0000638 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639 p2cread = GetStdHandle(STD_INPUT_HANDLE)
640 elif stdin == PIPE:
641 p2cread, p2cwrite = CreatePipe(None, 0)
642 # Detach and turn into fd
643 p2cwrite = p2cwrite.Detach()
644 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000645 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 p2cread = msvcrt.get_osfhandle(stdin)
647 else:
648 # Assuming file-like object
649 p2cread = msvcrt.get_osfhandle(stdin.fileno())
650 p2cread = self._make_inheritable(p2cread)
651
Peter Astrandd38ddf42005-02-10 08:32:50 +0000652 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000653 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
654 elif stdout == PIPE:
655 c2pread, c2pwrite = CreatePipe(None, 0)
656 # Detach and turn into fd
657 c2pread = c2pread.Detach()
658 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000659 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660 c2pwrite = msvcrt.get_osfhandle(stdout)
661 else:
662 # Assuming file-like object
663 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
664 c2pwrite = self._make_inheritable(c2pwrite)
665
Peter Astrandd38ddf42005-02-10 08:32:50 +0000666 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 errwrite = GetStdHandle(STD_ERROR_HANDLE)
668 elif stderr == PIPE:
669 errread, errwrite = CreatePipe(None, 0)
670 # Detach and turn into fd
671 errread = errread.Detach()
672 errread = msvcrt.open_osfhandle(errread, 0)
673 elif stderr == STDOUT:
674 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000675 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676 errwrite = msvcrt.get_osfhandle(stderr)
677 else:
678 # Assuming file-like object
679 errwrite = msvcrt.get_osfhandle(stderr.fileno())
680 errwrite = self._make_inheritable(errwrite)
681
682 return (p2cread, p2cwrite,
683 c2pread, c2pwrite,
684 errread, errwrite)
685
686
687 def _make_inheritable(self, handle):
688 """Return a duplicate of handle, which is inheritable"""
689 return DuplicateHandle(GetCurrentProcess(), handle,
690 GetCurrentProcess(), 0, 1,
691 DUPLICATE_SAME_ACCESS)
692
693
694 def _find_w9xpopen(self):
695 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000696 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
697 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000698 if not os.path.exists(w9xpopen):
699 # Eeek - file-not-found - possibly an embedding
700 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000701 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
702 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000704 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
705 "needed for Popen to work with your "
706 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707 return w9xpopen
708
Tim Peterse718f612004-10-12 21:51:32 +0000709
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 def _execute_child(self, args, executable, preexec_fn, close_fds,
711 cwd, env, universal_newlines,
712 startupinfo, creationflags, shell,
713 p2cread, p2cwrite,
714 c2pread, c2pwrite,
715 errread, errwrite):
716 """Execute program (MS Windows version)"""
717
Peter Astrandc26516b2005-02-21 08:13:02 +0000718 if not isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 args = list2cmdline(args)
720
Peter Astrandc1d65362004-11-07 14:30:34 +0000721 # Process startup details
722 default_startupinfo = STARTUPINFO()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000723 if startupinfo is None:
Peter Astrandc1d65362004-11-07 14:30:34 +0000724 startupinfo = default_startupinfo
725 if not None in (p2cread, c2pwrite, errwrite):
726 startupinfo.dwFlags |= STARTF_USESTDHANDLES
727 startupinfo.hStdInput = p2cread
728 startupinfo.hStdOutput = c2pwrite
729 startupinfo.hStdError = errwrite
730
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000732 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
733 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 comspec = os.environ.get("COMSPEC", "cmd.exe")
735 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000736 if (GetVersion() >= 0x80000000L or
737 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 # Win9x, or using command.com on NT. We need to
739 # use the w9xpopen intermediate program. For more
740 # information, see KB Q150956
741 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
742 w9xpopen = self._find_w9xpopen()
743 args = '"%s" %s' % (w9xpopen, args)
744 # Not passing CREATE_NEW_CONSOLE has been known to
745 # cause random failures on win9x. Specifically a
746 # dialog: "Your program accessed mem currently in
747 # use at xxx" and a hopeful warning about the
748 # stability of your system. Cost is Ctrl+C wont
749 # kill children.
750 creationflags |= CREATE_NEW_CONSOLE
751
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 # Start the process
753 try:
754 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000755 # no special security
756 None, None,
757 # must inherit handles to pass std
758 # handles
759 1,
760 creationflags,
761 env,
762 cwd,
763 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 except pywintypes.error, e:
765 # Translate pywintypes.error to WindowsError, which is
766 # a subclass of OSError. FIXME: We should really
767 # translate errno using _sys_errlist (or simliar), but
768 # how can this be done from Python?
769 raise WindowsError(*e.args)
770
771 # Retain the process handle, but close the thread handle
772 self._handle = hp
773 self.pid = pid
774 ht.Close()
775
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000776 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 # handles that only the child should have open. You need
778 # to make sure that no handles to the write end of the
779 # output pipe are maintained in this process or else the
780 # pipe will not close when the child process exits and the
781 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000782 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000783 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000784 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000786 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 errwrite.Close()
788
Tim Peterse718f612004-10-12 21:51:32 +0000789
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 def poll(self):
791 """Check if child process has terminated. Returns returncode
792 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000793 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
795 self.returncode = GetExitCodeProcess(self._handle)
796 _active.remove(self)
797 return self.returncode
798
799
800 def wait(self):
801 """Wait for child process to terminate. Returns returncode
802 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000803 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 obj = WaitForSingleObject(self._handle, INFINITE)
805 self.returncode = GetExitCodeProcess(self._handle)
806 _active.remove(self)
807 return self.returncode
808
809
810 def _readerthread(self, fh, buffer):
811 buffer.append(fh.read())
812
813
814 def communicate(self, input=None):
815 """Interact with process: Send data to stdin. Read data from
816 stdout and stderr, until end-of-file is reached. Wait for
817 process to terminate. The optional input argument should be a
818 string to be sent to the child process, or None, if no data
819 should be sent to the child.
820
821 communicate() returns a tuple (stdout, stderr)."""
822 stdout = None # Return
823 stderr = None # Return
824
825 if self.stdout:
826 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000827 stdout_thread = threading.Thread(target=self._readerthread,
828 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 stdout_thread.setDaemon(True)
830 stdout_thread.start()
831 if self.stderr:
832 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000833 stderr_thread = threading.Thread(target=self._readerthread,
834 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 stderr_thread.setDaemon(True)
836 stderr_thread.start()
837
838 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000839 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 self.stdin.write(input)
841 self.stdin.close()
842
843 if self.stdout:
844 stdout_thread.join()
845 if self.stderr:
846 stderr_thread.join()
847
848 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000849 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000851 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852 stderr = stderr[0]
853
854 # Translate newlines, if requested. We cannot let the file
855 # object do the translation: It is based on stdio, which is
856 # impossible to combine with select (unless forcing no
857 # buffering).
858 if self.universal_newlines and hasattr(open, 'newlines'):
859 if stdout:
860 stdout = self._translate_newlines(stdout)
861 if stderr:
862 stderr = self._translate_newlines(stderr)
863
864 self.wait()
865 return (stdout, stderr)
866
867 else:
868 #
869 # POSIX methods
870 #
871 def _get_handles(self, stdin, stdout, stderr):
872 """Construct and return tupel with IO objects:
873 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
874 """
875 p2cread, p2cwrite = None, None
876 c2pread, c2pwrite = None, None
877 errread, errwrite = None, None
878
Peter Astrandd38ddf42005-02-10 08:32:50 +0000879 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 pass
881 elif stdin == PIPE:
882 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000883 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884 p2cread = stdin
885 else:
886 # Assuming file-like object
887 p2cread = stdin.fileno()
888
Peter Astrandd38ddf42005-02-10 08:32:50 +0000889 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 pass
891 elif stdout == PIPE:
892 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000893 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894 c2pwrite = stdout
895 else:
896 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000897 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 pass
901 elif stderr == PIPE:
902 errread, errwrite = os.pipe()
903 elif stderr == STDOUT:
904 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000905 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000906 errwrite = stderr
907 else:
908 # Assuming file-like object
909 errwrite = stderr.fileno()
910
911 return (p2cread, p2cwrite,
912 c2pread, c2pwrite,
913 errread, errwrite)
914
915
916 def _set_cloexec_flag(self, fd):
917 try:
918 cloexec_flag = fcntl.FD_CLOEXEC
919 except AttributeError:
920 cloexec_flag = 1
921
922 old = fcntl.fcntl(fd, fcntl.F_GETFD)
923 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
924
925
926 def _close_fds(self, but):
927 for i in range(3, MAXFD):
928 if i == but:
929 continue
930 try:
931 os.close(i)
932 except:
933 pass
Tim Peterse718f612004-10-12 21:51:32 +0000934
935
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000936 def _execute_child(self, args, executable, preexec_fn, close_fds,
937 cwd, env, universal_newlines,
938 startupinfo, creationflags, shell,
939 p2cread, p2cwrite,
940 c2pread, c2pwrite,
941 errread, errwrite):
942 """Execute program (POSIX version)"""
943
Peter Astrandc26516b2005-02-21 08:13:02 +0000944 if isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 args = [args]
946
947 if shell:
948 args = ["/bin/sh", "-c"] + args
949
Peter Astrandd38ddf42005-02-10 08:32:50 +0000950 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 executable = args[0]
952
953 # For transferring possible exec failure from child to parent
954 # The first char specifies the exception type: 0 means
955 # OSError, 1 means some other error.
956 errpipe_read, errpipe_write = os.pipe()
957 self._set_cloexec_flag(errpipe_write)
958
959 self.pid = os.fork()
960 if self.pid == 0:
961 # Child
962 try:
963 # Close parent's pipe ends
964 if p2cwrite:
965 os.close(p2cwrite)
966 if c2pread:
967 os.close(c2pread)
968 if errread:
969 os.close(errread)
970 os.close(errpipe_read)
971
972 # Dup fds for child
973 if p2cread:
974 os.dup2(p2cread, 0)
975 if c2pwrite:
976 os.dup2(c2pwrite, 1)
977 if errwrite:
978 os.dup2(errwrite, 2)
979
980 # Close pipe fds. Make sure we doesn't close the same
981 # fd more than once.
982 if p2cread:
983 os.close(p2cread)
984 if c2pwrite and c2pwrite not in (p2cread,):
985 os.close(c2pwrite)
986 if errwrite and errwrite not in (p2cread, c2pwrite):
987 os.close(errwrite)
988
989 # Close all other fds, if asked for
990 if close_fds:
991 self._close_fds(but=errpipe_write)
992
Peter Astrandd38ddf42005-02-10 08:32:50 +0000993 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000994 os.chdir(cwd)
995
996 if preexec_fn:
997 apply(preexec_fn)
998
Peter Astrandd38ddf42005-02-10 08:32:50 +0000999 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 os.execvp(executable, args)
1001 else:
1002 os.execvpe(executable, args, env)
1003
1004 except:
1005 exc_type, exc_value, tb = sys.exc_info()
1006 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001007 exc_lines = traceback.format_exception(exc_type,
1008 exc_value,
1009 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 exc_value.child_traceback = ''.join(exc_lines)
1011 os.write(errpipe_write, pickle.dumps(exc_value))
1012
1013 # This exitcode won't be reported to applications, so it
1014 # really doesn't matter what we return.
1015 os._exit(255)
1016
1017 # Parent
1018 os.close(errpipe_write)
1019 if p2cread and p2cwrite:
1020 os.close(p2cread)
1021 if c2pwrite and c2pread:
1022 os.close(c2pwrite)
1023 if errwrite and errread:
1024 os.close(errwrite)
1025
1026 # Wait for exec to fail or succeed; possibly raising exception
1027 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1028 os.close(errpipe_read)
1029 if data != "":
Peter Astrandf791d7a2005-01-01 09:38:57 +00001030 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031 child_exception = pickle.loads(data)
1032 raise child_exception
1033
1034
1035 def _handle_exitstatus(self, sts):
1036 if os.WIFSIGNALED(sts):
1037 self.returncode = -os.WTERMSIG(sts)
1038 elif os.WIFEXITED(sts):
1039 self.returncode = os.WEXITSTATUS(sts)
1040 else:
1041 # Should never happen
1042 raise RuntimeError("Unknown child exit status!")
1043
1044 _active.remove(self)
1045
Tim Peterse718f612004-10-12 21:51:32 +00001046
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 def poll(self):
1048 """Check if child process has terminated. Returns returncode
1049 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001050 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051 try:
1052 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1053 if pid == self.pid:
1054 self._handle_exitstatus(sts)
1055 except os.error:
1056 pass
1057 return self.returncode
1058
1059
1060 def wait(self):
1061 """Wait for child process to terminate. Returns returncode
1062 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001063 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001064 pid, sts = os.waitpid(self.pid, 0)
1065 self._handle_exitstatus(sts)
1066 return self.returncode
1067
1068
1069 def communicate(self, input=None):
1070 """Interact with process: Send data to stdin. Read data from
1071 stdout and stderr, until end-of-file is reached. Wait for
1072 process to terminate. The optional input argument should be a
1073 string to be sent to the child process, or None, if no data
1074 should be sent to the child.
1075
1076 communicate() returns a tuple (stdout, stderr)."""
1077 read_set = []
1078 write_set = []
1079 stdout = None # Return
1080 stderr = None # Return
1081
1082 if self.stdin:
1083 # Flush stdio buffer. This might block, if the user has
1084 # been writing to .stdin in an uncontrolled fashion.
1085 self.stdin.flush()
1086 if input:
1087 write_set.append(self.stdin)
1088 else:
1089 self.stdin.close()
1090 if self.stdout:
1091 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001092 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093 if self.stderr:
1094 read_set.append(self.stderr)
1095 stderr = []
1096
1097 while read_set or write_set:
1098 rlist, wlist, xlist = select.select(read_set, write_set, [])
1099
1100 if self.stdin in wlist:
1101 # When select has indicated that the file is writable,
1102 # we can write up to PIPE_BUF bytes without risk
1103 # blocking. POSIX defines PIPE_BUF >= 512
1104 bytes_written = os.write(self.stdin.fileno(), input[:512])
1105 input = input[bytes_written:]
1106 if not input:
1107 self.stdin.close()
1108 write_set.remove(self.stdin)
1109
1110 if self.stdout in rlist:
1111 data = os.read(self.stdout.fileno(), 1024)
1112 if data == "":
1113 self.stdout.close()
1114 read_set.remove(self.stdout)
1115 stdout.append(data)
1116
1117 if self.stderr in rlist:
1118 data = os.read(self.stderr.fileno(), 1024)
1119 if data == "":
1120 self.stderr.close()
1121 read_set.remove(self.stderr)
1122 stderr.append(data)
1123
1124 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001125 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001126 stdout = ''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001127 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001128 stderr = ''.join(stderr)
1129
1130 # Translate newlines, if requested. We cannot let the file
1131 # object do the translation: It is based on stdio, which is
1132 # impossible to combine with select (unless forcing no
1133 # buffering).
1134 if self.universal_newlines and hasattr(open, 'newlines'):
1135 if stdout:
1136 stdout = self._translate_newlines(stdout)
1137 if stderr:
1138 stderr = self._translate_newlines(stderr)
1139
1140 self.wait()
1141 return (stdout, stderr)
1142
1143
1144def _demo_posix():
1145 #
1146 # Example 1: Simple redirection: Get process list
1147 #
1148 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1149 print "Process list:"
1150 print plist
1151
1152 #
1153 # Example 2: Change uid before executing child
1154 #
1155 if os.getuid() == 0:
1156 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1157 p.wait()
1158
1159 #
1160 # Example 3: Connecting several subprocesses
1161 #
1162 print "Looking for 'hda'..."
1163 p1 = Popen(["dmesg"], stdout=PIPE)
1164 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1165 print repr(p2.communicate()[0])
1166
1167 #
1168 # Example 4: Catch execution error
1169 #
1170 print
1171 print "Trying a weird file..."
1172 try:
1173 print Popen(["/this/path/does/not/exist"]).communicate()
1174 except OSError, e:
1175 if e.errno == errno.ENOENT:
1176 print "The file didn't exist. I thought so..."
1177 print "Child traceback:"
1178 print e.child_traceback
1179 else:
1180 print "Error", e.errno
1181 else:
1182 print >>sys.stderr, "Gosh. No error."
1183
1184
1185def _demo_windows():
1186 #
1187 # Example 1: Connecting several subprocesses
1188 #
1189 print "Looking for 'PROMPT' in set output..."
1190 p1 = Popen("set", stdout=PIPE, shell=True)
1191 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1192 print repr(p2.communicate()[0])
1193
1194 #
1195 # Example 2: Simple execution of program
1196 #
1197 print "Executing calc..."
1198 p = Popen("calc")
1199 p.wait()
1200
1201
1202if __name__ == "__main__":
1203 if mswindows:
1204 _demo_windows()
1205 else:
1206 _demo_posix()