blob: c4a7a65179231a4d0d0813890fc088f0d0b1e991 [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#
5# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se>
6#
Peter Astrand69bf13f2005-02-14 08:56:32 +00007# Licensed to PSF under a Contributor Agreement.
8#
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009# By obtaining, using, and/or copying this software and/or its
10# associated documentation, you agree that you have read, understood,
11# and will comply with the following terms and conditions:
12#
13# Permission to use, copy, modify, and distribute this software and
14# its associated documentation for any purpose and without fee is
15# hereby granted, provided that the above copyright notice appears in
16# all copies, and that both that copyright notice and this permission
17# notice appear in supporting documentation, and that the name of the
18# author not be used in advertising or publicity pertaining to
19# distribution of the software without specific, written prior
20# permission.
21#
22# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
23# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
24# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
25# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
26# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
27# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
28# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29
Raymond Hettinger837dd932004-10-17 16:36:53 +000030r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000031
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000032This module allows you to spawn processes, connect to their
33input/output/error pipes, and obtain their return codes. This module
34intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035
36os.system
37os.spawn*
38os.popen*
39popen2.*
40commands.*
41
42Information about how the subprocess module can be used to replace these
43modules and functions can be found below.
44
45
46
47Using the subprocess module
48===========================
49This module defines one class called Popen:
50
51class Popen(args, bufsize=0, executable=None,
52 stdin=None, stdout=None, stderr=None,
53 preexec_fn=None, close_fds=False, shell=False,
54 cwd=None, env=None, universal_newlines=False,
55 startupinfo=None, creationflags=0):
56
57
58Arguments are:
59
60args should be a string, or a sequence of program arguments. The
61program to execute is normally the first item in the args sequence or
62string, but can be explicitly set by using the executable argument.
63
64On UNIX, with shell=False (default): In this case, the Popen class
65uses os.execvp() to execute the child program. args should normally
66be a sequence. A string will be treated as a sequence with the string
67as the only item (the program to execute).
68
69On UNIX, with shell=True: If args is a string, it specifies the
70command string to execute through the shell. If args is a sequence,
71the first item specifies the command string, and any additional items
72will be treated as additional shell arguments.
73
74On Windows: the Popen class uses CreateProcess() to execute the child
75program, which operates on strings. If args is a sequence, it will be
76converted to a string using the list2cmdline method. Please note that
77not all MS Windows applications interpret the command line the same
78way: The list2cmdline is designed for applications using the same
79rules as the MS C runtime.
80
81bufsize, if given, has the same meaning as the corresponding argument
82to the built-in open() function: 0 means unbuffered, 1 means line
83buffered, any other positive value means use a buffer of
84(approximately) that size. A negative bufsize means to use the system
85default, which usually means fully buffered. The default value for
86bufsize is 0 (unbuffered).
87
88stdin, stdout and stderr specify the executed programs' standard
89input, standard output and standard error file handles, respectively.
90Valid values are PIPE, an existing file descriptor (a positive
91integer), an existing file object, and None. PIPE indicates that a
92new pipe to the child should be created. With None, no redirection
93will occur; the child's file handles will be inherited from the
94parent. Additionally, stderr can be STDOUT, which indicates that the
95stderr data from the applications should be captured into the same
96file handle as for stdout.
97
98If preexec_fn is set to a callable object, this object will be called
99in the child process just before the child is executed.
100
101If close_fds is true, all file descriptors except 0, 1 and 2 will be
102closed before the child process is executed.
103
104if shell is true, the specified command will be executed through the
105shell.
106
107If cwd is not None, the current directory will be changed to cwd
108before the child is executed.
109
110If env is not None, it defines the environment variables for the new
111process.
112
113If universal_newlines is true, the file objects stdout and stderr are
114opened as a text files, but lines may be terminated by any of '\n',
115the Unix end-of-line convention, '\r', the Macintosh convention or
116'\r\n', the Windows convention. All of these external representations
117are seen as '\n' by the Python program. Note: This feature is only
118available if Python is built with universal newline support (the
119default). Also, the newlines attribute of the file objects stdout,
120stdin and stderr are not updated by the communicate() method.
121
122The startupinfo and creationflags, if given, will be passed to the
123underlying CreateProcess() function. They can specify things such as
124appearance of the main window and priority for the new process.
125(Windows only)
126
127
128This module also defines two shortcut functions:
129
Peter Astrand5f5e1412004-12-05 20:15:36 +0000130call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131 Run command with arguments. Wait for command to complete, then
132 return the returncode attribute.
133
134 The arguments are the same as for the Popen constructor. Example:
135
136 retcode = call(["ls", "-l"])
137
Peter Astrand454f7672005-01-01 09:36:35 +0000138check_call(*popenargs, **kwargs):
139 Run command with arguments. Wait for command to complete. If the
140 exit code was zero then return, otherwise raise
141 CalledProcessError. The CalledProcessError object will have the
142 return code in the errno attribute.
143
144 The arguments are the same as for the Popen constructor. Example:
145
146 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147
148Exceptions
149----------
150Exceptions raised in the child process, before the new program has
151started to execute, will be re-raised in the parent. Additionally,
152the exception object will have one extra attribute called
153'child_traceback', which is a string containing traceback information
154from the childs point of view.
155
156The most common exception raised is OSError. This occurs, for
157example, when trying to execute a non-existent file. Applications
158should prepare for OSErrors.
159
160A ValueError will be raised if Popen is called with invalid arguments.
161
Peter Astrand454f7672005-01-01 09:36:35 +0000162check_call() will raise CalledProcessError, which is a subclass of
163OSError, if the called process returns a non-zero return code.
164
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165
166Security
167--------
168Unlike some other popen functions, this implementation will never call
169/bin/sh implicitly. This means that all characters, including shell
170metacharacters, can safely be passed to child processes.
171
172
173Popen objects
174=============
175Instances of the Popen class have the following methods:
176
177poll()
178 Check if child process has terminated. Returns returncode
179 attribute.
180
181wait()
182 Wait for child process to terminate. Returns returncode attribute.
183
184communicate(input=None)
185 Interact with process: Send data to stdin. Read data from stdout
186 and stderr, until end-of-file is reached. Wait for process to
187 terminate. The optional stdin argument should be a string to be
188 sent to the child process, or None, if no data should be sent to
189 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000190
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000191 communicate() returns a tuple (stdout, stderr).
192
193 Note: The data read is buffered in memory, so do not use this
194 method if the data size is large or unlimited.
195
196The following attributes are also available:
197
198stdin
199 If the stdin argument is PIPE, this attribute is a file object
200 that provides input to the child process. Otherwise, it is None.
201
202stdout
203 If the stdout argument is PIPE, this attribute is a file object
204 that provides output from the child process. Otherwise, it is
205 None.
206
207stderr
208 If the stderr argument is PIPE, this attribute is file object that
209 provides error output from the child process. Otherwise, it is
210 None.
211
212pid
213 The process ID of the child process.
214
215returncode
216 The child return code. A None value indicates that the process
217 hasn't terminated yet. A negative value -N indicates that the
218 child was terminated by signal N (UNIX only).
219
220
221Replacing older functions with the subprocess module
222====================================================
223In this section, "a ==> b" means that b can be used as a replacement
224for a.
225
226Note: All functions in this section fail (more or less) silently if
227the executed program cannot be found; this module raises an OSError
228exception.
229
230In the following examples, we assume that the subprocess module is
231imported with "from subprocess import *".
232
233
234Replacing /bin/sh shell backquote
235---------------------------------
236output=`mycmd myarg`
237==>
238output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
239
240
241Replacing shell pipe line
242-------------------------
243output=`dmesg | grep hda`
244==>
245p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000246p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247output = p2.communicate()[0]
248
249
250Replacing os.system()
251---------------------
252sts = os.system("mycmd" + " myarg")
253==>
254p = Popen("mycmd" + " myarg", shell=True)
255sts = os.waitpid(p.pid, 0)
256
257Note:
258
259* Calling the program through the shell is usually not required.
260
261* It's easier to look at the returncode attribute than the
262 exitstatus.
263
264A more real-world example would look like this:
265
266try:
267 retcode = call("mycmd" + " myarg", shell=True)
268 if retcode < 0:
269 print >>sys.stderr, "Child was terminated by signal", -retcode
270 else:
271 print >>sys.stderr, "Child returned", retcode
272except OSError, e:
273 print >>sys.stderr, "Execution failed:", e
274
275
276Replacing os.spawn*
277-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000278P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279
280pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
281==>
282pid = Popen(["/bin/mycmd", "myarg"]).pid
283
284
285P_WAIT example:
286
287retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
288==>
289retcode = call(["/bin/mycmd", "myarg"])
290
291
Tim Peterse718f612004-10-12 21:51:32 +0000292Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
294os.spawnvp(os.P_NOWAIT, path, args)
295==>
296Popen([path] + args[1:])
297
298
Tim Peterse718f612004-10-12 21:51:32 +0000299Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300
301os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
302==>
303Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
304
305
Tim Peterse718f612004-10-12 21:51:32 +0000306Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307-------------------
308pipe = os.popen(cmd, mode='r', bufsize)
309==>
310pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
311
312pipe = os.popen(cmd, mode='w', bufsize)
313==>
314pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
315
316
317(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
318==>
319p = Popen(cmd, shell=True, bufsize=bufsize,
320 stdin=PIPE, stdout=PIPE, close_fds=True)
321(child_stdin, child_stdout) = (p.stdin, p.stdout)
322
323
324(child_stdin,
325 child_stdout,
326 child_stderr) = os.popen3(cmd, mode, bufsize)
327==>
328p = Popen(cmd, shell=True, bufsize=bufsize,
329 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
330(child_stdin,
331 child_stdout,
332 child_stderr) = (p.stdin, p.stdout, p.stderr)
333
334
335(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
336==>
337p = Popen(cmd, shell=True, bufsize=bufsize,
338 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
339(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
340
341
342Replacing popen2.*
343------------------
344Note: If the cmd argument to popen2 functions is a string, the command
345is executed through /bin/sh. If it is a list, the command is directly
346executed.
347
348(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
349==>
350p = Popen(["somestring"], shell=True, bufsize=bufsize
351 stdin=PIPE, stdout=PIPE, close_fds=True)
352(child_stdout, child_stdin) = (p.stdout, p.stdin)
353
354
355(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
356==>
357p = Popen(["mycmd", "myarg"], bufsize=bufsize,
358 stdin=PIPE, stdout=PIPE, close_fds=True)
359(child_stdout, child_stdin) = (p.stdout, p.stdin)
360
361The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
362except that:
363
364* subprocess.Popen raises an exception if the execution fails
365* the capturestderr argument is replaced with the stderr argument.
366* stdin=PIPE and stdout=PIPE must be specified.
367* popen2 closes all filedescriptors by default, but you have to specify
Tim Peterse718f612004-10-12 21:51:32 +0000368 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000369
370
371"""
372
373import sys
374mswindows = (sys.platform == "win32")
375
376import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000377import traceback
378
Peter Astrand454f7672005-01-01 09:36:35 +0000379# Exception classes used by this module.
380class CalledProcessError(OSError):
381 """This exception is raised when a process run by check_call() returns
382 a non-zero exit status. The exit status will be stored in the
383 errno attribute. This exception is a subclass of
384 OSError."""
385
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386if mswindows:
387 import threading
388 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000389 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000391 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
392 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
393 from win32api import GetCurrentProcess, DuplicateHandle, \
394 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000395 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000397 from win32process import CreateProcess, STARTUPINFO, \
398 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000399 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000401 else:
402 from _subprocess import *
403 class STARTUPINFO:
404 dwFlags = 0
405 hStdInput = None
406 hStdOutput = None
407 hStdError = None
408 class pywintypes:
409 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410else:
411 import select
412 import errno
413 import fcntl
414 import pickle
415
Peter Astrand454f7672005-01-01 09:36:35 +0000416__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417
418try:
419 MAXFD = os.sysconf("SC_OPEN_MAX")
420except:
421 MAXFD = 256
422
423# True/False does not exist on 2.2.0
424try:
425 False
426except NameError:
427 False = 0
428 True = 1
429
430_active = []
431
432def _cleanup():
433 for inst in _active[:]:
434 inst.poll()
435
436PIPE = -1
437STDOUT = -2
438
439
Peter Astrand5f5e1412004-12-05 20:15:36 +0000440def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 """Run command with arguments. Wait for command to complete, then
442 return the returncode attribute.
443
444 The arguments are the same as for the Popen constructor. Example:
445
446 retcode = call(["ls", "-l"])
447 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000448 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449
450
Peter Astrand454f7672005-01-01 09:36:35 +0000451def check_call(*popenargs, **kwargs):
452 """Run command with arguments. Wait for command to complete. If
453 the exit code was zero then return, otherwise raise
454 CalledProcessError. The CalledProcessError object will have the
455 return code in the errno attribute.
456
457 The arguments are the same as for the Popen constructor. Example:
458
459 check_call(["ls", "-l"])
460 """
461 retcode = call(*popenargs, **kwargs)
462 cmd = kwargs.get("args")
463 if cmd is None:
464 cmd = popenargs[0]
465 if retcode:
466 raise CalledProcessError(retcode, "Command %s returned non-zero exit status" % cmd)
467 return retcode
468
469
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470def list2cmdline(seq):
471 """
472 Translate a sequence of arguments into a command line
473 string, using the same rules as the MS C runtime:
474
475 1) Arguments are delimited by white space, which is either a
476 space or a tab.
477
478 2) A string surrounded by double quotation marks is
479 interpreted as a single argument, regardless of white space
480 contained within. A quoted string can be embedded in an
481 argument.
482
483 3) A double quotation mark preceded by a backslash is
484 interpreted as a literal double quotation mark.
485
486 4) Backslashes are interpreted literally, unless they
487 immediately precede a double quotation mark.
488
489 5) If backslashes immediately precede a double quotation mark,
490 every pair of backslashes is interpreted as a literal
491 backslash. If the number of backslashes is odd, the last
492 backslash escapes the next double quotation mark as
493 described in rule 3.
494 """
495
496 # See
497 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
498 result = []
499 needquote = False
500 for arg in seq:
501 bs_buf = []
502
503 # Add a space to separate this argument from the others
504 if result:
505 result.append(' ')
506
507 needquote = (" " in arg) or ("\t" in arg)
508 if needquote:
509 result.append('"')
510
511 for c in arg:
512 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000513 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 bs_buf.append(c)
515 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000516 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 result.append('\\' * len(bs_buf)*2)
518 bs_buf = []
519 result.append('\\"')
520 else:
521 # Normal char
522 if bs_buf:
523 result.extend(bs_buf)
524 bs_buf = []
525 result.append(c)
526
Tim Peterse718f612004-10-12 21:51:32 +0000527 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 if bs_buf:
529 result.extend(bs_buf)
530
531 if needquote:
532 result.append('"')
533
534 return ''.join(result)
535
536
537class Popen(object):
538 def __init__(self, args, bufsize=0, executable=None,
539 stdin=None, stdout=None, stderr=None,
540 preexec_fn=None, close_fds=False, shell=False,
541 cwd=None, env=None, universal_newlines=False,
542 startupinfo=None, creationflags=0):
543 """Create new Popen instance."""
544 _cleanup()
545
Peter Astrand738131d2004-11-30 21:04:45 +0000546 if not isinstance(bufsize, (int, long)):
547 raise TypeError("bufsize must be an integer")
548
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000550 if preexec_fn is not None:
551 raise ValueError("preexec_fn is not supported on Windows "
552 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000554 raise ValueError("close_fds is not supported on Windows "
555 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 else:
557 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000558 if startupinfo is not None:
559 raise ValueError("startupinfo is only supported on Windows "
560 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000562 raise ValueError("creationflags is only supported on Windows "
563 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564
Tim Peterse718f612004-10-12 21:51:32 +0000565 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 self.stdout = None
567 self.stderr = None
568 self.pid = None
569 self.returncode = None
570 self.universal_newlines = universal_newlines
571
572 # Input and output objects. The general principle is like
573 # this:
574 #
575 # Parent Child
576 # ------ -----
577 # p2cwrite ---stdin---> p2cread
578 # c2pread <--stdout--- c2pwrite
579 # errread <--stderr--- errwrite
580 #
581 # On POSIX, the child objects are file descriptors. On
582 # Windows, these are Windows file handles. The parent objects
583 # are file descriptors on both platforms. The parent objects
584 # are None when not using PIPEs. The child objects are None
585 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000586
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 (p2cread, p2cwrite,
588 c2pread, c2pwrite,
589 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
590
591 self._execute_child(args, executable, preexec_fn, close_fds,
592 cwd, env, universal_newlines,
593 startupinfo, creationflags, shell,
594 p2cread, p2cwrite,
595 c2pread, c2pwrite,
596 errread, errwrite)
597
598 if p2cwrite:
599 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
600 if c2pread:
601 if universal_newlines:
602 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
603 else:
604 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
605 if errread:
606 if universal_newlines:
607 self.stderr = os.fdopen(errread, 'rU', bufsize)
608 else:
609 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000610
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 _active.append(self)
612
613
614 def _translate_newlines(self, data):
615 data = data.replace("\r\n", "\n")
616 data = data.replace("\r", "\n")
617 return data
618
619
620 if mswindows:
621 #
622 # Windows methods
623 #
624 def _get_handles(self, stdin, stdout, stderr):
625 """Construct and return tupel with IO objects:
626 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
627 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000628 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000630
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 p2cread, p2cwrite = None, None
632 c2pread, c2pwrite = None, None
633 errread, errwrite = None, None
634
Peter Astrandd38ddf42005-02-10 08:32:50 +0000635 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 p2cread = GetStdHandle(STD_INPUT_HANDLE)
637 elif stdin == PIPE:
638 p2cread, p2cwrite = CreatePipe(None, 0)
639 # Detach and turn into fd
640 p2cwrite = p2cwrite.Detach()
641 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000642 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 p2cread = msvcrt.get_osfhandle(stdin)
644 else:
645 # Assuming file-like object
646 p2cread = msvcrt.get_osfhandle(stdin.fileno())
647 p2cread = self._make_inheritable(p2cread)
648
Peter Astrandd38ddf42005-02-10 08:32:50 +0000649 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
651 elif stdout == PIPE:
652 c2pread, c2pwrite = CreatePipe(None, 0)
653 # Detach and turn into fd
654 c2pread = c2pread.Detach()
655 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000656 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657 c2pwrite = msvcrt.get_osfhandle(stdout)
658 else:
659 # Assuming file-like object
660 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
661 c2pwrite = self._make_inheritable(c2pwrite)
662
Peter Astrandd38ddf42005-02-10 08:32:50 +0000663 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 errwrite = GetStdHandle(STD_ERROR_HANDLE)
665 elif stderr == PIPE:
666 errread, errwrite = CreatePipe(None, 0)
667 # Detach and turn into fd
668 errread = errread.Detach()
669 errread = msvcrt.open_osfhandle(errread, 0)
670 elif stderr == STDOUT:
671 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000672 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673 errwrite = msvcrt.get_osfhandle(stderr)
674 else:
675 # Assuming file-like object
676 errwrite = msvcrt.get_osfhandle(stderr.fileno())
677 errwrite = self._make_inheritable(errwrite)
678
679 return (p2cread, p2cwrite,
680 c2pread, c2pwrite,
681 errread, errwrite)
682
683
684 def _make_inheritable(self, handle):
685 """Return a duplicate of handle, which is inheritable"""
686 return DuplicateHandle(GetCurrentProcess(), handle,
687 GetCurrentProcess(), 0, 1,
688 DUPLICATE_SAME_ACCESS)
689
690
691 def _find_w9xpopen(self):
692 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000693 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
694 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000695 if not os.path.exists(w9xpopen):
696 # Eeek - file-not-found - possibly an embedding
697 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000698 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
699 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000701 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
702 "needed for Popen to work with your "
703 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704 return w9xpopen
705
Tim Peterse718f612004-10-12 21:51:32 +0000706
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000707 def _execute_child(self, args, executable, preexec_fn, close_fds,
708 cwd, env, universal_newlines,
709 startupinfo, creationflags, shell,
710 p2cread, p2cwrite,
711 c2pread, c2pwrite,
712 errread, errwrite):
713 """Execute program (MS Windows version)"""
714
Raymond Hettingerf7153662005-02-07 14:16:21 +0000715 if not isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 args = list2cmdline(args)
717
Peter Astrandc1d65362004-11-07 14:30:34 +0000718 # Process startup details
719 default_startupinfo = STARTUPINFO()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000720 if startupinfo is None:
Peter Astrandc1d65362004-11-07 14:30:34 +0000721 startupinfo = default_startupinfo
722 if not None in (p2cread, c2pwrite, errwrite):
723 startupinfo.dwFlags |= STARTF_USESTDHANDLES
724 startupinfo.hStdInput = p2cread
725 startupinfo.hStdOutput = c2pwrite
726 startupinfo.hStdError = errwrite
727
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000729 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
730 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 comspec = os.environ.get("COMSPEC", "cmd.exe")
732 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000733 if (GetVersion() >= 0x80000000L or
734 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735 # Win9x, or using command.com on NT. We need to
736 # use the w9xpopen intermediate program. For more
737 # information, see KB Q150956
738 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
739 w9xpopen = self._find_w9xpopen()
740 args = '"%s" %s' % (w9xpopen, args)
741 # Not passing CREATE_NEW_CONSOLE has been known to
742 # cause random failures on win9x. Specifically a
743 # dialog: "Your program accessed mem currently in
744 # use at xxx" and a hopeful warning about the
745 # stability of your system. Cost is Ctrl+C wont
746 # kill children.
747 creationflags |= CREATE_NEW_CONSOLE
748
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000749 # Start the process
750 try:
751 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000752 # no special security
753 None, None,
754 # must inherit handles to pass std
755 # handles
756 1,
757 creationflags,
758 env,
759 cwd,
760 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 except pywintypes.error, e:
762 # Translate pywintypes.error to WindowsError, which is
763 # a subclass of OSError. FIXME: We should really
764 # translate errno using _sys_errlist (or simliar), but
765 # how can this be done from Python?
766 raise WindowsError(*e.args)
767
768 # Retain the process handle, but close the thread handle
769 self._handle = hp
770 self.pid = pid
771 ht.Close()
772
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000773 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774 # handles that only the child should have open. You need
775 # to make sure that no handles to the write end of the
776 # output pipe are maintained in this process or else the
777 # pipe will not close when the child process exits and the
778 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000779 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000781 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000783 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000784 errwrite.Close()
785
Tim Peterse718f612004-10-12 21:51:32 +0000786
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 def poll(self):
788 """Check if child process has terminated. Returns returncode
789 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000790 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
792 self.returncode = GetExitCodeProcess(self._handle)
793 _active.remove(self)
794 return self.returncode
795
796
797 def wait(self):
798 """Wait for child process to terminate. Returns returncode
799 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000800 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 obj = WaitForSingleObject(self._handle, INFINITE)
802 self.returncode = GetExitCodeProcess(self._handle)
803 _active.remove(self)
804 return self.returncode
805
806
807 def _readerthread(self, fh, buffer):
808 buffer.append(fh.read())
809
810
811 def communicate(self, input=None):
812 """Interact with process: Send data to stdin. Read data from
813 stdout and stderr, until end-of-file is reached. Wait for
814 process to terminate. The optional input argument should be a
815 string to be sent to the child process, or None, if no data
816 should be sent to the child.
817
818 communicate() returns a tuple (stdout, stderr)."""
819 stdout = None # Return
820 stderr = None # Return
821
822 if self.stdout:
823 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000824 stdout_thread = threading.Thread(target=self._readerthread,
825 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 stdout_thread.setDaemon(True)
827 stdout_thread.start()
828 if self.stderr:
829 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000830 stderr_thread = threading.Thread(target=self._readerthread,
831 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 stderr_thread.setDaemon(True)
833 stderr_thread.start()
834
835 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000836 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837 self.stdin.write(input)
838 self.stdin.close()
839
840 if self.stdout:
841 stdout_thread.join()
842 if self.stderr:
843 stderr_thread.join()
844
845 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000846 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000848 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 stderr = stderr[0]
850
851 # Translate newlines, if requested. We cannot let the file
852 # object do the translation: It is based on stdio, which is
853 # impossible to combine with select (unless forcing no
854 # buffering).
855 if self.universal_newlines and hasattr(open, 'newlines'):
856 if stdout:
857 stdout = self._translate_newlines(stdout)
858 if stderr:
859 stderr = self._translate_newlines(stderr)
860
861 self.wait()
862 return (stdout, stderr)
863
864 else:
865 #
866 # POSIX methods
867 #
868 def _get_handles(self, stdin, stdout, stderr):
869 """Construct and return tupel with IO objects:
870 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
871 """
872 p2cread, p2cwrite = None, None
873 c2pread, c2pwrite = None, None
874 errread, errwrite = None, None
875
Peter Astrandd38ddf42005-02-10 08:32:50 +0000876 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877 pass
878 elif stdin == PIPE:
879 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000880 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 p2cread = stdin
882 else:
883 # Assuming file-like object
884 p2cread = stdin.fileno()
885
Peter Astrandd38ddf42005-02-10 08:32:50 +0000886 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887 pass
888 elif stdout == PIPE:
889 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000890 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 c2pwrite = stdout
892 else:
893 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000894 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895
Peter Astrandd38ddf42005-02-10 08:32:50 +0000896 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897 pass
898 elif stderr == PIPE:
899 errread, errwrite = os.pipe()
900 elif stderr == STDOUT:
901 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000902 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000903 errwrite = stderr
904 else:
905 # Assuming file-like object
906 errwrite = stderr.fileno()
907
908 return (p2cread, p2cwrite,
909 c2pread, c2pwrite,
910 errread, errwrite)
911
912
913 def _set_cloexec_flag(self, fd):
914 try:
915 cloexec_flag = fcntl.FD_CLOEXEC
916 except AttributeError:
917 cloexec_flag = 1
918
919 old = fcntl.fcntl(fd, fcntl.F_GETFD)
920 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
921
922
923 def _close_fds(self, but):
924 for i in range(3, MAXFD):
925 if i == but:
926 continue
927 try:
928 os.close(i)
929 except:
930 pass
Tim Peterse718f612004-10-12 21:51:32 +0000931
932
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 def _execute_child(self, args, executable, preexec_fn, close_fds,
934 cwd, env, universal_newlines,
935 startupinfo, creationflags, shell,
936 p2cread, p2cwrite,
937 c2pread, c2pwrite,
938 errread, errwrite):
939 """Execute program (POSIX version)"""
940
Raymond Hettingerf7153662005-02-07 14:16:21 +0000941 if isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000942 args = [args]
943
944 if shell:
945 args = ["/bin/sh", "-c"] + args
946
Peter Astrandd38ddf42005-02-10 08:32:50 +0000947 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 executable = args[0]
949
950 # For transferring possible exec failure from child to parent
951 # The first char specifies the exception type: 0 means
952 # OSError, 1 means some other error.
953 errpipe_read, errpipe_write = os.pipe()
954 self._set_cloexec_flag(errpipe_write)
955
956 self.pid = os.fork()
957 if self.pid == 0:
958 # Child
959 try:
960 # Close parent's pipe ends
961 if p2cwrite:
962 os.close(p2cwrite)
963 if c2pread:
964 os.close(c2pread)
965 if errread:
966 os.close(errread)
967 os.close(errpipe_read)
968
969 # Dup fds for child
970 if p2cread:
971 os.dup2(p2cread, 0)
972 if c2pwrite:
973 os.dup2(c2pwrite, 1)
974 if errwrite:
975 os.dup2(errwrite, 2)
976
977 # Close pipe fds. Make sure we doesn't close the same
978 # fd more than once.
979 if p2cread:
980 os.close(p2cread)
981 if c2pwrite and c2pwrite not in (p2cread,):
982 os.close(c2pwrite)
983 if errwrite and errwrite not in (p2cread, c2pwrite):
984 os.close(errwrite)
985
986 # Close all other fds, if asked for
987 if close_fds:
988 self._close_fds(but=errpipe_write)
989
Peter Astrandd38ddf42005-02-10 08:32:50 +0000990 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000991 os.chdir(cwd)
992
993 if preexec_fn:
994 apply(preexec_fn)
995
Peter Astrandd38ddf42005-02-10 08:32:50 +0000996 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 os.execvp(executable, args)
998 else:
999 os.execvpe(executable, args, env)
1000
1001 except:
1002 exc_type, exc_value, tb = sys.exc_info()
1003 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001004 exc_lines = traceback.format_exception(exc_type,
1005 exc_value,
1006 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 exc_value.child_traceback = ''.join(exc_lines)
1008 os.write(errpipe_write, pickle.dumps(exc_value))
1009
1010 # This exitcode won't be reported to applications, so it
1011 # really doesn't matter what we return.
1012 os._exit(255)
1013
1014 # Parent
1015 os.close(errpipe_write)
1016 if p2cread and p2cwrite:
1017 os.close(p2cread)
1018 if c2pwrite and c2pread:
1019 os.close(c2pwrite)
1020 if errwrite and errread:
1021 os.close(errwrite)
1022
1023 # Wait for exec to fail or succeed; possibly raising exception
1024 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1025 os.close(errpipe_read)
1026 if data != "":
Peter Astrandf791d7a2005-01-01 09:38:57 +00001027 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001028 child_exception = pickle.loads(data)
1029 raise child_exception
1030
1031
1032 def _handle_exitstatus(self, sts):
1033 if os.WIFSIGNALED(sts):
1034 self.returncode = -os.WTERMSIG(sts)
1035 elif os.WIFEXITED(sts):
1036 self.returncode = os.WEXITSTATUS(sts)
1037 else:
1038 # Should never happen
1039 raise RuntimeError("Unknown child exit status!")
1040
1041 _active.remove(self)
1042
Tim Peterse718f612004-10-12 21:51:32 +00001043
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044 def poll(self):
1045 """Check if child process has terminated. Returns returncode
1046 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001047 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001048 try:
1049 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1050 if pid == self.pid:
1051 self._handle_exitstatus(sts)
1052 except os.error:
1053 pass
1054 return self.returncode
1055
1056
1057 def wait(self):
1058 """Wait for child process to terminate. Returns returncode
1059 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001060 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061 pid, sts = os.waitpid(self.pid, 0)
1062 self._handle_exitstatus(sts)
1063 return self.returncode
1064
1065
1066 def communicate(self, input=None):
1067 """Interact with process: Send data to stdin. Read data from
1068 stdout and stderr, until end-of-file is reached. Wait for
1069 process to terminate. The optional input argument should be a
1070 string to be sent to the child process, or None, if no data
1071 should be sent to the child.
1072
1073 communicate() returns a tuple (stdout, stderr)."""
1074 read_set = []
1075 write_set = []
1076 stdout = None # Return
1077 stderr = None # Return
1078
1079 if self.stdin:
1080 # Flush stdio buffer. This might block, if the user has
1081 # been writing to .stdin in an uncontrolled fashion.
1082 self.stdin.flush()
1083 if input:
1084 write_set.append(self.stdin)
1085 else:
1086 self.stdin.close()
1087 if self.stdout:
1088 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001089 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 if self.stderr:
1091 read_set.append(self.stderr)
1092 stderr = []
1093
1094 while read_set or write_set:
1095 rlist, wlist, xlist = select.select(read_set, write_set, [])
1096
1097 if self.stdin in wlist:
1098 # When select has indicated that the file is writable,
1099 # we can write up to PIPE_BUF bytes without risk
1100 # blocking. POSIX defines PIPE_BUF >= 512
1101 bytes_written = os.write(self.stdin.fileno(), input[:512])
1102 input = input[bytes_written:]
1103 if not input:
1104 self.stdin.close()
1105 write_set.remove(self.stdin)
1106
1107 if self.stdout in rlist:
1108 data = os.read(self.stdout.fileno(), 1024)
1109 if data == "":
1110 self.stdout.close()
1111 read_set.remove(self.stdout)
1112 stdout.append(data)
1113
1114 if self.stderr in rlist:
1115 data = os.read(self.stderr.fileno(), 1024)
1116 if data == "":
1117 self.stderr.close()
1118 read_set.remove(self.stderr)
1119 stderr.append(data)
1120
1121 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001122 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001123 stdout = ''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001124 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001125 stderr = ''.join(stderr)
1126
1127 # Translate newlines, if requested. We cannot let the file
1128 # object do the translation: It is based on stdio, which is
1129 # impossible to combine with select (unless forcing no
1130 # buffering).
1131 if self.universal_newlines and hasattr(open, 'newlines'):
1132 if stdout:
1133 stdout = self._translate_newlines(stdout)
1134 if stderr:
1135 stderr = self._translate_newlines(stderr)
1136
1137 self.wait()
1138 return (stdout, stderr)
1139
1140
1141def _demo_posix():
1142 #
1143 # Example 1: Simple redirection: Get process list
1144 #
1145 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1146 print "Process list:"
1147 print plist
1148
1149 #
1150 # Example 2: Change uid before executing child
1151 #
1152 if os.getuid() == 0:
1153 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1154 p.wait()
1155
1156 #
1157 # Example 3: Connecting several subprocesses
1158 #
1159 print "Looking for 'hda'..."
1160 p1 = Popen(["dmesg"], stdout=PIPE)
1161 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1162 print repr(p2.communicate()[0])
1163
1164 #
1165 # Example 4: Catch execution error
1166 #
1167 print
1168 print "Trying a weird file..."
1169 try:
1170 print Popen(["/this/path/does/not/exist"]).communicate()
1171 except OSError, e:
1172 if e.errno == errno.ENOENT:
1173 print "The file didn't exist. I thought so..."
1174 print "Child traceback:"
1175 print e.child_traceback
1176 else:
1177 print "Error", e.errno
1178 else:
1179 print >>sys.stderr, "Gosh. No error."
1180
1181
1182def _demo_windows():
1183 #
1184 # Example 1: Connecting several subprocesses
1185 #
1186 print "Looking for 'PROMPT' in set output..."
1187 p1 = Popen("set", stdout=PIPE, shell=True)
1188 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1189 print repr(p2.communicate()[0])
1190
1191 #
1192 # Example 2: Simple execution of program
1193 #
1194 print "Executing calc..."
1195 p = Popen("calc")
1196 p.wait()
1197
1198
1199if __name__ == "__main__":
1200 if mswindows:
1201 _demo_windows()
1202 else:
1203 _demo_posix()