blob: 4cf67ac35b034a2d3a77786a3e872fca37524471 [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#
7# By obtaining, using, and/or copying this software and/or its
8# associated documentation, you agree that you have read, understood,
9# and will comply with the following terms and conditions:
10#
11# Permission to use, copy, modify, and distribute this software and
12# its associated documentation for any purpose and without fee is
13# hereby granted, provided that the above copyright notice appears in
14# all copies, and that both that copyright notice and this permission
15# notice appear in supporting documentation, and that the name of the
16# author not be used in advertising or publicity pertaining to
17# distribution of the software without specific, written prior
18# permission.
19#
20# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
22# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
23# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
24# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
25# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
26# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27
Raymond Hettinger837dd932004-10-17 16:36:53 +000028r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000030This module allows you to spawn processes, connect to their
31input/output/error pipes, and obtain their return codes. This module
32intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033
34os.system
35os.spawn*
36os.popen*
37popen2.*
38commands.*
39
40Information about how the subprocess module can be used to replace these
41modules and functions can be found below.
42
43
44
45Using the subprocess module
46===========================
47This module defines one class called Popen:
48
49class Popen(args, bufsize=0, executable=None,
50 stdin=None, stdout=None, stderr=None,
51 preexec_fn=None, close_fds=False, shell=False,
52 cwd=None, env=None, universal_newlines=False,
53 startupinfo=None, creationflags=0):
54
55
56Arguments are:
57
58args should be a string, or a sequence of program arguments. The
59program to execute is normally the first item in the args sequence or
60string, but can be explicitly set by using the executable argument.
61
62On UNIX, with shell=False (default): In this case, the Popen class
63uses os.execvp() to execute the child program. args should normally
64be a sequence. A string will be treated as a sequence with the string
65as the only item (the program to execute).
66
67On UNIX, with shell=True: If args is a string, it specifies the
68command string to execute through the shell. If args is a sequence,
69the first item specifies the command string, and any additional items
70will be treated as additional shell arguments.
71
72On Windows: the Popen class uses CreateProcess() to execute the child
73program, which operates on strings. If args is a sequence, it will be
74converted to a string using the list2cmdline method. Please note that
75not all MS Windows applications interpret the command line the same
76way: The list2cmdline is designed for applications using the same
77rules as the MS C runtime.
78
79bufsize, if given, has the same meaning as the corresponding argument
80to the built-in open() function: 0 means unbuffered, 1 means line
81buffered, any other positive value means use a buffer of
82(approximately) that size. A negative bufsize means to use the system
83default, which usually means fully buffered. The default value for
84bufsize is 0 (unbuffered).
85
86stdin, stdout and stderr specify the executed programs' standard
87input, standard output and standard error file handles, respectively.
88Valid values are PIPE, an existing file descriptor (a positive
89integer), an existing file object, and None. PIPE indicates that a
90new pipe to the child should be created. With None, no redirection
91will occur; the child's file handles will be inherited from the
92parent. Additionally, stderr can be STDOUT, which indicates that the
93stderr data from the applications should be captured into the same
94file handle as for stdout.
95
96If preexec_fn is set to a callable object, this object will be called
97in the child process just before the child is executed.
98
99If close_fds is true, all file descriptors except 0, 1 and 2 will be
100closed before the child process is executed.
101
102if shell is true, the specified command will be executed through the
103shell.
104
105If cwd is not None, the current directory will be changed to cwd
106before the child is executed.
107
108If env is not None, it defines the environment variables for the new
109process.
110
111If universal_newlines is true, the file objects stdout and stderr are
112opened as a text files, but lines may be terminated by any of '\n',
113the Unix end-of-line convention, '\r', the Macintosh convention or
114'\r\n', the Windows convention. All of these external representations
115are seen as '\n' by the Python program. Note: This feature is only
116available if Python is built with universal newline support (the
117default). Also, the newlines attribute of the file objects stdout,
118stdin and stderr are not updated by the communicate() method.
119
120The startupinfo and creationflags, if given, will be passed to the
121underlying CreateProcess() function. They can specify things such as
122appearance of the main window and priority for the new process.
123(Windows only)
124
125
126This module also defines two shortcut functions:
127
Peter Astrand5f5e1412004-12-05 20:15:36 +0000128call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 Run command with arguments. Wait for command to complete, then
130 return the returncode attribute.
131
132 The arguments are the same as for the Popen constructor. Example:
133
134 retcode = call(["ls", "-l"])
135
Peter Astrand454f7672005-01-01 09:36:35 +0000136check_call(*popenargs, **kwargs):
137 Run command with arguments. Wait for command to complete. If the
138 exit code was zero then return, otherwise raise
139 CalledProcessError. The CalledProcessError object will have the
140 return code in the errno attribute.
141
142 The arguments are the same as for the Popen constructor. Example:
143
144 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145
146Exceptions
147----------
148Exceptions raised in the child process, before the new program has
149started to execute, will be re-raised in the parent. Additionally,
150the exception object will have one extra attribute called
151'child_traceback', which is a string containing traceback information
152from the childs point of view.
153
154The most common exception raised is OSError. This occurs, for
155example, when trying to execute a non-existent file. Applications
156should prepare for OSErrors.
157
158A ValueError will be raised if Popen is called with invalid arguments.
159
Peter Astrand454f7672005-01-01 09:36:35 +0000160check_call() will raise CalledProcessError, which is a subclass of
161OSError, if the called process returns a non-zero return code.
162
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163
164Security
165--------
166Unlike some other popen functions, this implementation will never call
167/bin/sh implicitly. This means that all characters, including shell
168metacharacters, can safely be passed to child processes.
169
170
171Popen objects
172=============
173Instances of the Popen class have the following methods:
174
175poll()
176 Check if child process has terminated. Returns returncode
177 attribute.
178
179wait()
180 Wait for child process to terminate. Returns returncode attribute.
181
182communicate(input=None)
183 Interact with process: Send data to stdin. Read data from stdout
184 and stderr, until end-of-file is reached. Wait for process to
185 terminate. The optional stdin argument should be a string to be
186 sent to the child process, or None, if no data should be sent to
187 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000188
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 communicate() returns a tuple (stdout, stderr).
190
191 Note: The data read is buffered in memory, so do not use this
192 method if the data size is large or unlimited.
193
194The following attributes are also available:
195
196stdin
197 If the stdin argument is PIPE, this attribute is a file object
198 that provides input to the child process. Otherwise, it is None.
199
200stdout
201 If the stdout argument is PIPE, this attribute is a file object
202 that provides output from the child process. Otherwise, it is
203 None.
204
205stderr
206 If the stderr argument is PIPE, this attribute is file object that
207 provides error output from the child process. Otherwise, it is
208 None.
209
210pid
211 The process ID of the child process.
212
213returncode
214 The child return code. A None value indicates that the process
215 hasn't terminated yet. A negative value -N indicates that the
216 child was terminated by signal N (UNIX only).
217
218
219Replacing older functions with the subprocess module
220====================================================
221In this section, "a ==> b" means that b can be used as a replacement
222for a.
223
224Note: All functions in this section fail (more or less) silently if
225the executed program cannot be found; this module raises an OSError
226exception.
227
228In the following examples, we assume that the subprocess module is
229imported with "from subprocess import *".
230
231
232Replacing /bin/sh shell backquote
233---------------------------------
234output=`mycmd myarg`
235==>
236output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
237
238
239Replacing shell pipe line
240-------------------------
241output=`dmesg | grep hda`
242==>
243p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000244p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245output = p2.communicate()[0]
246
247
248Replacing os.system()
249---------------------
250sts = os.system("mycmd" + " myarg")
251==>
252p = Popen("mycmd" + " myarg", shell=True)
253sts = os.waitpid(p.pid, 0)
254
255Note:
256
257* Calling the program through the shell is usually not required.
258
259* It's easier to look at the returncode attribute than the
260 exitstatus.
261
262A more real-world example would look like this:
263
264try:
265 retcode = call("mycmd" + " myarg", shell=True)
266 if retcode < 0:
267 print >>sys.stderr, "Child was terminated by signal", -retcode
268 else:
269 print >>sys.stderr, "Child returned", retcode
270except OSError, e:
271 print >>sys.stderr, "Execution failed:", e
272
273
274Replacing os.spawn*
275-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000276P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277
278pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
279==>
280pid = Popen(["/bin/mycmd", "myarg"]).pid
281
282
283P_WAIT example:
284
285retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
286==>
287retcode = call(["/bin/mycmd", "myarg"])
288
289
Tim Peterse718f612004-10-12 21:51:32 +0000290Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292os.spawnvp(os.P_NOWAIT, path, args)
293==>
294Popen([path] + args[1:])
295
296
Tim Peterse718f612004-10-12 21:51:32 +0000297Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298
299os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
300==>
301Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
302
303
Tim Peterse718f612004-10-12 21:51:32 +0000304Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305-------------------
306pipe = os.popen(cmd, mode='r', bufsize)
307==>
308pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
309
310pipe = os.popen(cmd, mode='w', bufsize)
311==>
312pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
313
314
315(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
316==>
317p = Popen(cmd, shell=True, bufsize=bufsize,
318 stdin=PIPE, stdout=PIPE, close_fds=True)
319(child_stdin, child_stdout) = (p.stdin, p.stdout)
320
321
322(child_stdin,
323 child_stdout,
324 child_stderr) = os.popen3(cmd, mode, bufsize)
325==>
326p = Popen(cmd, shell=True, bufsize=bufsize,
327 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
328(child_stdin,
329 child_stdout,
330 child_stderr) = (p.stdin, p.stdout, p.stderr)
331
332
333(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
334==>
335p = Popen(cmd, shell=True, bufsize=bufsize,
336 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
337(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
338
339
340Replacing popen2.*
341------------------
342Note: If the cmd argument to popen2 functions is a string, the command
343is executed through /bin/sh. If it is a list, the command is directly
344executed.
345
346(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
347==>
348p = Popen(["somestring"], shell=True, bufsize=bufsize
349 stdin=PIPE, stdout=PIPE, close_fds=True)
350(child_stdout, child_stdin) = (p.stdout, p.stdin)
351
352
353(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
354==>
355p = Popen(["mycmd", "myarg"], bufsize=bufsize,
356 stdin=PIPE, stdout=PIPE, close_fds=True)
357(child_stdout, child_stdin) = (p.stdout, p.stdin)
358
359The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
360except that:
361
362* subprocess.Popen raises an exception if the execution fails
363* the capturestderr argument is replaced with the stderr argument.
364* stdin=PIPE and stdout=PIPE must be specified.
365* popen2 closes all filedescriptors by default, but you have to specify
Tim Peterse718f612004-10-12 21:51:32 +0000366 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
368
369"""
370
371import sys
372mswindows = (sys.platform == "win32")
373
374import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375import traceback
376
Peter Astrand454f7672005-01-01 09:36:35 +0000377# Exception classes used by this module.
378class CalledProcessError(OSError):
379 """This exception is raised when a process run by check_call() returns
380 a non-zero exit status. The exit status will be stored in the
381 errno attribute. This exception is a subclass of
382 OSError."""
383
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384if mswindows:
385 import threading
386 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000387 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000389 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
390 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
391 from win32api import GetCurrentProcess, DuplicateHandle, \
392 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000393 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000395 from win32process import CreateProcess, STARTUPINFO, \
396 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000397 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000399 else:
400 from _subprocess import *
401 class STARTUPINFO:
402 dwFlags = 0
403 hStdInput = None
404 hStdOutput = None
405 hStdError = None
406 class pywintypes:
407 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408else:
409 import select
410 import errno
411 import fcntl
412 import pickle
413
Peter Astrand454f7672005-01-01 09:36:35 +0000414__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415
416try:
417 MAXFD = os.sysconf("SC_OPEN_MAX")
418except:
419 MAXFD = 256
420
421# True/False does not exist on 2.2.0
422try:
423 False
424except NameError:
425 False = 0
426 True = 1
427
428_active = []
429
430def _cleanup():
431 for inst in _active[:]:
432 inst.poll()
433
434PIPE = -1
435STDOUT = -2
436
437
Peter Astrand5f5e1412004-12-05 20:15:36 +0000438def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 """Run command with arguments. Wait for command to complete, then
440 return the returncode attribute.
441
442 The arguments are the same as for the Popen constructor. Example:
443
444 retcode = call(["ls", "-l"])
445 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000446 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447
448
Peter Astrand454f7672005-01-01 09:36:35 +0000449def check_call(*popenargs, **kwargs):
450 """Run command with arguments. Wait for command to complete. If
451 the exit code was zero then return, otherwise raise
452 CalledProcessError. The CalledProcessError object will have the
453 return code in the errno attribute.
454
455 The arguments are the same as for the Popen constructor. Example:
456
457 check_call(["ls", "-l"])
458 """
459 retcode = call(*popenargs, **kwargs)
460 cmd = kwargs.get("args")
461 if cmd is None:
462 cmd = popenargs[0]
463 if retcode:
464 raise CalledProcessError(retcode, "Command %s returned non-zero exit status" % cmd)
465 return retcode
466
467
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468def list2cmdline(seq):
469 """
470 Translate a sequence of arguments into a command line
471 string, using the same rules as the MS C runtime:
472
473 1) Arguments are delimited by white space, which is either a
474 space or a tab.
475
476 2) A string surrounded by double quotation marks is
477 interpreted as a single argument, regardless of white space
478 contained within. A quoted string can be embedded in an
479 argument.
480
481 3) A double quotation mark preceded by a backslash is
482 interpreted as a literal double quotation mark.
483
484 4) Backslashes are interpreted literally, unless they
485 immediately precede a double quotation mark.
486
487 5) If backslashes immediately precede a double quotation mark,
488 every pair of backslashes is interpreted as a literal
489 backslash. If the number of backslashes is odd, the last
490 backslash escapes the next double quotation mark as
491 described in rule 3.
492 """
493
494 # See
495 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
496 result = []
497 needquote = False
498 for arg in seq:
499 bs_buf = []
500
501 # Add a space to separate this argument from the others
502 if result:
503 result.append(' ')
504
505 needquote = (" " in arg) or ("\t" in arg)
506 if needquote:
507 result.append('"')
508
509 for c in arg:
510 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000511 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 bs_buf.append(c)
513 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000514 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515 result.append('\\' * len(bs_buf)*2)
516 bs_buf = []
517 result.append('\\"')
518 else:
519 # Normal char
520 if bs_buf:
521 result.extend(bs_buf)
522 bs_buf = []
523 result.append(c)
524
Tim Peterse718f612004-10-12 21:51:32 +0000525 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 if bs_buf:
527 result.extend(bs_buf)
528
529 if needquote:
530 result.append('"')
531
532 return ''.join(result)
533
534
535class Popen(object):
536 def __init__(self, args, bufsize=0, executable=None,
537 stdin=None, stdout=None, stderr=None,
538 preexec_fn=None, close_fds=False, shell=False,
539 cwd=None, env=None, universal_newlines=False,
540 startupinfo=None, creationflags=0):
541 """Create new Popen instance."""
542 _cleanup()
543
Peter Astrand738131d2004-11-30 21:04:45 +0000544 if not isinstance(bufsize, (int, long)):
545 raise TypeError("bufsize must be an integer")
546
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000548 if preexec_fn is not None:
549 raise ValueError("preexec_fn is not supported on Windows "
550 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000552 raise ValueError("close_fds is not supported on Windows "
553 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 else:
555 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000556 if startupinfo is not None:
557 raise ValueError("startupinfo is only supported on Windows "
558 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000560 raise ValueError("creationflags is only supported on Windows "
561 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562
Tim Peterse718f612004-10-12 21:51:32 +0000563 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 self.stdout = None
565 self.stderr = None
566 self.pid = None
567 self.returncode = None
568 self.universal_newlines = universal_newlines
569
570 # Input and output objects. The general principle is like
571 # this:
572 #
573 # Parent Child
574 # ------ -----
575 # p2cwrite ---stdin---> p2cread
576 # c2pread <--stdout--- c2pwrite
577 # errread <--stderr--- errwrite
578 #
579 # On POSIX, the child objects are file descriptors. On
580 # Windows, these are Windows file handles. The parent objects
581 # are file descriptors on both platforms. The parent objects
582 # are None when not using PIPEs. The child objects are None
583 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 (p2cread, p2cwrite,
586 c2pread, c2pwrite,
587 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
588
589 self._execute_child(args, executable, preexec_fn, close_fds,
590 cwd, env, universal_newlines,
591 startupinfo, creationflags, shell,
592 p2cread, p2cwrite,
593 c2pread, c2pwrite,
594 errread, errwrite)
595
596 if p2cwrite:
597 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
598 if c2pread:
599 if universal_newlines:
600 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
601 else:
602 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
603 if errread:
604 if universal_newlines:
605 self.stderr = os.fdopen(errread, 'rU', bufsize)
606 else:
607 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000608
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 _active.append(self)
610
611
612 def _translate_newlines(self, data):
613 data = data.replace("\r\n", "\n")
614 data = data.replace("\r", "\n")
615 return data
616
617
618 if mswindows:
619 #
620 # Windows methods
621 #
622 def _get_handles(self, stdin, stdout, stderr):
623 """Construct and return tupel with IO objects:
624 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
625 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000626 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000628
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 p2cread, p2cwrite = None, None
630 c2pread, c2pwrite = None, None
631 errread, errwrite = None, None
632
Peter Astrandd38ddf42005-02-10 08:32:50 +0000633 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 p2cread = GetStdHandle(STD_INPUT_HANDLE)
635 elif stdin == PIPE:
636 p2cread, p2cwrite = CreatePipe(None, 0)
637 # Detach and turn into fd
638 p2cwrite = p2cwrite.Detach()
639 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000640 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 p2cread = msvcrt.get_osfhandle(stdin)
642 else:
643 # Assuming file-like object
644 p2cread = msvcrt.get_osfhandle(stdin.fileno())
645 p2cread = self._make_inheritable(p2cread)
646
Peter Astrandd38ddf42005-02-10 08:32:50 +0000647 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
649 elif stdout == PIPE:
650 c2pread, c2pwrite = CreatePipe(None, 0)
651 # Detach and turn into fd
652 c2pread = c2pread.Detach()
653 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000654 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 c2pwrite = msvcrt.get_osfhandle(stdout)
656 else:
657 # Assuming file-like object
658 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
659 c2pwrite = self._make_inheritable(c2pwrite)
660
Peter Astrandd38ddf42005-02-10 08:32:50 +0000661 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 errwrite = GetStdHandle(STD_ERROR_HANDLE)
663 elif stderr == PIPE:
664 errread, errwrite = CreatePipe(None, 0)
665 # Detach and turn into fd
666 errread = errread.Detach()
667 errread = msvcrt.open_osfhandle(errread, 0)
668 elif stderr == STDOUT:
669 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000670 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 errwrite = msvcrt.get_osfhandle(stderr)
672 else:
673 # Assuming file-like object
674 errwrite = msvcrt.get_osfhandle(stderr.fileno())
675 errwrite = self._make_inheritable(errwrite)
676
677 return (p2cread, p2cwrite,
678 c2pread, c2pwrite,
679 errread, errwrite)
680
681
682 def _make_inheritable(self, handle):
683 """Return a duplicate of handle, which is inheritable"""
684 return DuplicateHandle(GetCurrentProcess(), handle,
685 GetCurrentProcess(), 0, 1,
686 DUPLICATE_SAME_ACCESS)
687
688
689 def _find_w9xpopen(self):
690 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000691 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
692 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693 if not os.path.exists(w9xpopen):
694 # Eeek - file-not-found - possibly an embedding
695 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000696 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
697 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000698 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000699 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
700 "needed for Popen to work with your "
701 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 return w9xpopen
703
Tim Peterse718f612004-10-12 21:51:32 +0000704
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705 def _execute_child(self, args, executable, preexec_fn, close_fds,
706 cwd, env, universal_newlines,
707 startupinfo, creationflags, shell,
708 p2cread, p2cwrite,
709 c2pread, c2pwrite,
710 errread, errwrite):
711 """Execute program (MS Windows version)"""
712
Raymond Hettingerf7153662005-02-07 14:16:21 +0000713 if not isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 args = list2cmdline(args)
715
Peter Astrandc1d65362004-11-07 14:30:34 +0000716 # Process startup details
717 default_startupinfo = STARTUPINFO()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000718 if startupinfo is None:
Peter Astrandc1d65362004-11-07 14:30:34 +0000719 startupinfo = default_startupinfo
720 if not None in (p2cread, c2pwrite, errwrite):
721 startupinfo.dwFlags |= STARTF_USESTDHANDLES
722 startupinfo.hStdInput = p2cread
723 startupinfo.hStdOutput = c2pwrite
724 startupinfo.hStdError = errwrite
725
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000727 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
728 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 comspec = os.environ.get("COMSPEC", "cmd.exe")
730 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000731 if (GetVersion() >= 0x80000000L or
732 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 # Win9x, or using command.com on NT. We need to
734 # use the w9xpopen intermediate program. For more
735 # information, see KB Q150956
736 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
737 w9xpopen = self._find_w9xpopen()
738 args = '"%s" %s' % (w9xpopen, args)
739 # Not passing CREATE_NEW_CONSOLE has been known to
740 # cause random failures on win9x. Specifically a
741 # dialog: "Your program accessed mem currently in
742 # use at xxx" and a hopeful warning about the
743 # stability of your system. Cost is Ctrl+C wont
744 # kill children.
745 creationflags |= CREATE_NEW_CONSOLE
746
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 # Start the process
748 try:
749 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000750 # no special security
751 None, None,
752 # must inherit handles to pass std
753 # handles
754 1,
755 creationflags,
756 env,
757 cwd,
758 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 except pywintypes.error, e:
760 # Translate pywintypes.error to WindowsError, which is
761 # a subclass of OSError. FIXME: We should really
762 # translate errno using _sys_errlist (or simliar), but
763 # how can this be done from Python?
764 raise WindowsError(*e.args)
765
766 # Retain the process handle, but close the thread handle
767 self._handle = hp
768 self.pid = pid
769 ht.Close()
770
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000771 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 # handles that only the child should have open. You need
773 # to make sure that no handles to the write end of the
774 # output pipe are maintained in this process or else the
775 # pipe will not close when the child process exits and the
776 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000777 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000779 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000781 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782 errwrite.Close()
783
Tim Peterse718f612004-10-12 21:51:32 +0000784
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 def poll(self):
786 """Check if child process has terminated. Returns returncode
787 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000788 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000789 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
790 self.returncode = GetExitCodeProcess(self._handle)
791 _active.remove(self)
792 return self.returncode
793
794
795 def wait(self):
796 """Wait for child process to terminate. Returns returncode
797 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000798 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799 obj = WaitForSingleObject(self._handle, INFINITE)
800 self.returncode = GetExitCodeProcess(self._handle)
801 _active.remove(self)
802 return self.returncode
803
804
805 def _readerthread(self, fh, buffer):
806 buffer.append(fh.read())
807
808
809 def communicate(self, input=None):
810 """Interact with process: Send data to stdin. Read data from
811 stdout and stderr, until end-of-file is reached. Wait for
812 process to terminate. The optional input argument should be a
813 string to be sent to the child process, or None, if no data
814 should be sent to the child.
815
816 communicate() returns a tuple (stdout, stderr)."""
817 stdout = None # Return
818 stderr = None # Return
819
820 if self.stdout:
821 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000822 stdout_thread = threading.Thread(target=self._readerthread,
823 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 stdout_thread.setDaemon(True)
825 stdout_thread.start()
826 if self.stderr:
827 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000828 stderr_thread = threading.Thread(target=self._readerthread,
829 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 stderr_thread.setDaemon(True)
831 stderr_thread.start()
832
833 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000834 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 self.stdin.write(input)
836 self.stdin.close()
837
838 if self.stdout:
839 stdout_thread.join()
840 if self.stderr:
841 stderr_thread.join()
842
843 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000844 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000846 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 stderr = stderr[0]
848
849 # Translate newlines, if requested. We cannot let the file
850 # object do the translation: It is based on stdio, which is
851 # impossible to combine with select (unless forcing no
852 # buffering).
853 if self.universal_newlines and hasattr(open, 'newlines'):
854 if stdout:
855 stdout = self._translate_newlines(stdout)
856 if stderr:
857 stderr = self._translate_newlines(stderr)
858
859 self.wait()
860 return (stdout, stderr)
861
862 else:
863 #
864 # POSIX methods
865 #
866 def _get_handles(self, stdin, stdout, stderr):
867 """Construct and return tupel with IO objects:
868 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
869 """
870 p2cread, p2cwrite = None, None
871 c2pread, c2pwrite = None, None
872 errread, errwrite = None, None
873
Peter Astrandd38ddf42005-02-10 08:32:50 +0000874 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000875 pass
876 elif stdin == PIPE:
877 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000878 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 p2cread = stdin
880 else:
881 # Assuming file-like object
882 p2cread = stdin.fileno()
883
Peter Astrandd38ddf42005-02-10 08:32:50 +0000884 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885 pass
886 elif stdout == PIPE:
887 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000888 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 c2pwrite = stdout
890 else:
891 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000892 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893
Peter Astrandd38ddf42005-02-10 08:32:50 +0000894 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895 pass
896 elif stderr == PIPE:
897 errread, errwrite = os.pipe()
898 elif stderr == STDOUT:
899 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000900 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000901 errwrite = stderr
902 else:
903 # Assuming file-like object
904 errwrite = stderr.fileno()
905
906 return (p2cread, p2cwrite,
907 c2pread, c2pwrite,
908 errread, errwrite)
909
910
911 def _set_cloexec_flag(self, fd):
912 try:
913 cloexec_flag = fcntl.FD_CLOEXEC
914 except AttributeError:
915 cloexec_flag = 1
916
917 old = fcntl.fcntl(fd, fcntl.F_GETFD)
918 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
919
920
921 def _close_fds(self, but):
922 for i in range(3, MAXFD):
923 if i == but:
924 continue
925 try:
926 os.close(i)
927 except:
928 pass
Tim Peterse718f612004-10-12 21:51:32 +0000929
930
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 def _execute_child(self, args, executable, preexec_fn, close_fds,
932 cwd, env, universal_newlines,
933 startupinfo, creationflags, shell,
934 p2cread, p2cwrite,
935 c2pread, c2pwrite,
936 errread, errwrite):
937 """Execute program (POSIX version)"""
938
Raymond Hettingerf7153662005-02-07 14:16:21 +0000939 if isinstance(args, basestring):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 args = [args]
941
942 if shell:
943 args = ["/bin/sh", "-c"] + args
944
Peter Astrandd38ddf42005-02-10 08:32:50 +0000945 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946 executable = args[0]
947
948 # For transferring possible exec failure from child to parent
949 # The first char specifies the exception type: 0 means
950 # OSError, 1 means some other error.
951 errpipe_read, errpipe_write = os.pipe()
952 self._set_cloexec_flag(errpipe_write)
953
954 self.pid = os.fork()
955 if self.pid == 0:
956 # Child
957 try:
958 # Close parent's pipe ends
959 if p2cwrite:
960 os.close(p2cwrite)
961 if c2pread:
962 os.close(c2pread)
963 if errread:
964 os.close(errread)
965 os.close(errpipe_read)
966
967 # Dup fds for child
968 if p2cread:
969 os.dup2(p2cread, 0)
970 if c2pwrite:
971 os.dup2(c2pwrite, 1)
972 if errwrite:
973 os.dup2(errwrite, 2)
974
975 # Close pipe fds. Make sure we doesn't close the same
976 # fd more than once.
977 if p2cread:
978 os.close(p2cread)
979 if c2pwrite and c2pwrite not in (p2cread,):
980 os.close(c2pwrite)
981 if errwrite and errwrite not in (p2cread, c2pwrite):
982 os.close(errwrite)
983
984 # Close all other fds, if asked for
985 if close_fds:
986 self._close_fds(but=errpipe_write)
987
Peter Astrandd38ddf42005-02-10 08:32:50 +0000988 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000989 os.chdir(cwd)
990
991 if preexec_fn:
992 apply(preexec_fn)
993
Peter Astrandd38ddf42005-02-10 08:32:50 +0000994 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 os.execvp(executable, args)
996 else:
997 os.execvpe(executable, args, env)
998
999 except:
1000 exc_type, exc_value, tb = sys.exc_info()
1001 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001002 exc_lines = traceback.format_exception(exc_type,
1003 exc_value,
1004 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001005 exc_value.child_traceback = ''.join(exc_lines)
1006 os.write(errpipe_write, pickle.dumps(exc_value))
1007
1008 # This exitcode won't be reported to applications, so it
1009 # really doesn't matter what we return.
1010 os._exit(255)
1011
1012 # Parent
1013 os.close(errpipe_write)
1014 if p2cread and p2cwrite:
1015 os.close(p2cread)
1016 if c2pwrite and c2pread:
1017 os.close(c2pwrite)
1018 if errwrite and errread:
1019 os.close(errwrite)
1020
1021 # Wait for exec to fail or succeed; possibly raising exception
1022 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1023 os.close(errpipe_read)
1024 if data != "":
Peter Astrandf791d7a2005-01-01 09:38:57 +00001025 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001026 child_exception = pickle.loads(data)
1027 raise child_exception
1028
1029
1030 def _handle_exitstatus(self, sts):
1031 if os.WIFSIGNALED(sts):
1032 self.returncode = -os.WTERMSIG(sts)
1033 elif os.WIFEXITED(sts):
1034 self.returncode = os.WEXITSTATUS(sts)
1035 else:
1036 # Should never happen
1037 raise RuntimeError("Unknown child exit status!")
1038
1039 _active.remove(self)
1040
Tim Peterse718f612004-10-12 21:51:32 +00001041
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001042 def poll(self):
1043 """Check if child process has terminated. Returns returncode
1044 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001045 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001046 try:
1047 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1048 if pid == self.pid:
1049 self._handle_exitstatus(sts)
1050 except os.error:
1051 pass
1052 return self.returncode
1053
1054
1055 def wait(self):
1056 """Wait for child process to terminate. Returns returncode
1057 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001058 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059 pid, sts = os.waitpid(self.pid, 0)
1060 self._handle_exitstatus(sts)
1061 return self.returncode
1062
1063
1064 def communicate(self, input=None):
1065 """Interact with process: Send data to stdin. Read data from
1066 stdout and stderr, until end-of-file is reached. Wait for
1067 process to terminate. The optional input argument should be a
1068 string to be sent to the child process, or None, if no data
1069 should be sent to the child.
1070
1071 communicate() returns a tuple (stdout, stderr)."""
1072 read_set = []
1073 write_set = []
1074 stdout = None # Return
1075 stderr = None # Return
1076
1077 if self.stdin:
1078 # Flush stdio buffer. This might block, if the user has
1079 # been writing to .stdin in an uncontrolled fashion.
1080 self.stdin.flush()
1081 if input:
1082 write_set.append(self.stdin)
1083 else:
1084 self.stdin.close()
1085 if self.stdout:
1086 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001087 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001088 if self.stderr:
1089 read_set.append(self.stderr)
1090 stderr = []
1091
1092 while read_set or write_set:
1093 rlist, wlist, xlist = select.select(read_set, write_set, [])
1094
1095 if self.stdin in wlist:
1096 # When select has indicated that the file is writable,
1097 # we can write up to PIPE_BUF bytes without risk
1098 # blocking. POSIX defines PIPE_BUF >= 512
1099 bytes_written = os.write(self.stdin.fileno(), input[:512])
1100 input = input[bytes_written:]
1101 if not input:
1102 self.stdin.close()
1103 write_set.remove(self.stdin)
1104
1105 if self.stdout in rlist:
1106 data = os.read(self.stdout.fileno(), 1024)
1107 if data == "":
1108 self.stdout.close()
1109 read_set.remove(self.stdout)
1110 stdout.append(data)
1111
1112 if self.stderr in rlist:
1113 data = os.read(self.stderr.fileno(), 1024)
1114 if data == "":
1115 self.stderr.close()
1116 read_set.remove(self.stderr)
1117 stderr.append(data)
1118
1119 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001120 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001121 stdout = ''.join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001122 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001123 stderr = ''.join(stderr)
1124
1125 # Translate newlines, if requested. We cannot let the file
1126 # object do the translation: It is based on stdio, which is
1127 # impossible to combine with select (unless forcing no
1128 # buffering).
1129 if self.universal_newlines and hasattr(open, 'newlines'):
1130 if stdout:
1131 stdout = self._translate_newlines(stdout)
1132 if stderr:
1133 stderr = self._translate_newlines(stderr)
1134
1135 self.wait()
1136 return (stdout, stderr)
1137
1138
1139def _demo_posix():
1140 #
1141 # Example 1: Simple redirection: Get process list
1142 #
1143 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1144 print "Process list:"
1145 print plist
1146
1147 #
1148 # Example 2: Change uid before executing child
1149 #
1150 if os.getuid() == 0:
1151 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1152 p.wait()
1153
1154 #
1155 # Example 3: Connecting several subprocesses
1156 #
1157 print "Looking for 'hda'..."
1158 p1 = Popen(["dmesg"], stdout=PIPE)
1159 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1160 print repr(p2.communicate()[0])
1161
1162 #
1163 # Example 4: Catch execution error
1164 #
1165 print
1166 print "Trying a weird file..."
1167 try:
1168 print Popen(["/this/path/does/not/exist"]).communicate()
1169 except OSError, e:
1170 if e.errno == errno.ENOENT:
1171 print "The file didn't exist. I thought so..."
1172 print "Child traceback:"
1173 print e.child_traceback
1174 else:
1175 print "Error", e.errno
1176 else:
1177 print >>sys.stderr, "Gosh. No error."
1178
1179
1180def _demo_windows():
1181 #
1182 # Example 1: Connecting several subprocesses
1183 #
1184 print "Looking for 'PROMPT' in set output..."
1185 p1 = Popen("set", stdout=PIPE, shell=True)
1186 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1187 print repr(p2.communicate()[0])
1188
1189 #
1190 # Example 2: Simple execution of program
1191 #
1192 print "Executing calc..."
1193 p = Popen("calc")
1194 p.wait()
1195
1196
1197if __name__ == "__main__":
1198 if mswindows:
1199 _demo_windows()
1200 else:
1201 _demo_posix()