blob: 40b04fe39ffdf1f3582d53d3b72909bc51bdba89 [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
136
137Exceptions
138----------
139Exceptions raised in the child process, before the new program has
140started to execute, will be re-raised in the parent. Additionally,
141the exception object will have one extra attribute called
142'child_traceback', which is a string containing traceback information
143from the childs point of view.
144
145The most common exception raised is OSError. This occurs, for
146example, when trying to execute a non-existent file. Applications
147should prepare for OSErrors.
148
149A ValueError will be raised if Popen is called with invalid arguments.
150
151
152Security
153--------
154Unlike some other popen functions, this implementation will never call
155/bin/sh implicitly. This means that all characters, including shell
156metacharacters, can safely be passed to child processes.
157
158
159Popen objects
160=============
161Instances of the Popen class have the following methods:
162
163poll()
164 Check if child process has terminated. Returns returncode
165 attribute.
166
167wait()
168 Wait for child process to terminate. Returns returncode attribute.
169
170communicate(input=None)
171 Interact with process: Send data to stdin. Read data from stdout
172 and stderr, until end-of-file is reached. Wait for process to
173 terminate. The optional stdin argument should be a string to be
174 sent to the child process, or None, if no data should be sent to
175 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000176
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 communicate() returns a tuple (stdout, stderr).
178
179 Note: The data read is buffered in memory, so do not use this
180 method if the data size is large or unlimited.
181
182The following attributes are also available:
183
184stdin
185 If the stdin argument is PIPE, this attribute is a file object
186 that provides input to the child process. Otherwise, it is None.
187
188stdout
189 If the stdout argument is PIPE, this attribute is a file object
190 that provides output from the child process. Otherwise, it is
191 None.
192
193stderr
194 If the stderr argument is PIPE, this attribute is file object that
195 provides error output from the child process. Otherwise, it is
196 None.
197
198pid
199 The process ID of the child process.
200
201returncode
202 The child return code. A None value indicates that the process
203 hasn't terminated yet. A negative value -N indicates that the
204 child was terminated by signal N (UNIX only).
205
206
207Replacing older functions with the subprocess module
208====================================================
209In this section, "a ==> b" means that b can be used as a replacement
210for a.
211
212Note: All functions in this section fail (more or less) silently if
213the executed program cannot be found; this module raises an OSError
214exception.
215
216In the following examples, we assume that the subprocess module is
217imported with "from subprocess import *".
218
219
220Replacing /bin/sh shell backquote
221---------------------------------
222output=`mycmd myarg`
223==>
224output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
225
226
227Replacing shell pipe line
228-------------------------
229output=`dmesg | grep hda`
230==>
231p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000232p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233output = p2.communicate()[0]
234
235
236Replacing os.system()
237---------------------
238sts = os.system("mycmd" + " myarg")
239==>
240p = Popen("mycmd" + " myarg", shell=True)
241sts = os.waitpid(p.pid, 0)
242
243Note:
244
245* Calling the program through the shell is usually not required.
246
247* It's easier to look at the returncode attribute than the
248 exitstatus.
249
250A more real-world example would look like this:
251
252try:
253 retcode = call("mycmd" + " myarg", shell=True)
254 if retcode < 0:
255 print >>sys.stderr, "Child was terminated by signal", -retcode
256 else:
257 print >>sys.stderr, "Child returned", retcode
258except OSError, e:
259 print >>sys.stderr, "Execution failed:", e
260
261
262Replacing os.spawn*
263-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000264P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265
266pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
267==>
268pid = Popen(["/bin/mycmd", "myarg"]).pid
269
270
271P_WAIT example:
272
273retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
274==>
275retcode = call(["/bin/mycmd", "myarg"])
276
277
Tim Peterse718f612004-10-12 21:51:32 +0000278Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279
280os.spawnvp(os.P_NOWAIT, path, args)
281==>
282Popen([path] + args[1:])
283
284
Tim Peterse718f612004-10-12 21:51:32 +0000285Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286
287os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
288==>
289Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
290
291
Tim Peterse718f612004-10-12 21:51:32 +0000292Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293-------------------
294pipe = os.popen(cmd, mode='r', bufsize)
295==>
296pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
297
298pipe = os.popen(cmd, mode='w', bufsize)
299==>
300pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
301
302
303(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
304==>
305p = Popen(cmd, shell=True, bufsize=bufsize,
306 stdin=PIPE, stdout=PIPE, close_fds=True)
307(child_stdin, child_stdout) = (p.stdin, p.stdout)
308
309
310(child_stdin,
311 child_stdout,
312 child_stderr) = os.popen3(cmd, mode, bufsize)
313==>
314p = Popen(cmd, shell=True, bufsize=bufsize,
315 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
316(child_stdin,
317 child_stdout,
318 child_stderr) = (p.stdin, p.stdout, p.stderr)
319
320
321(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
322==>
323p = Popen(cmd, shell=True, bufsize=bufsize,
324 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
325(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
326
327
328Replacing popen2.*
329------------------
330Note: If the cmd argument to popen2 functions is a string, the command
331is executed through /bin/sh. If it is a list, the command is directly
332executed.
333
334(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
335==>
336p = Popen(["somestring"], shell=True, bufsize=bufsize
337 stdin=PIPE, stdout=PIPE, close_fds=True)
338(child_stdout, child_stdin) = (p.stdout, p.stdin)
339
340
341(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
342==>
343p = Popen(["mycmd", "myarg"], bufsize=bufsize,
344 stdin=PIPE, stdout=PIPE, close_fds=True)
345(child_stdout, child_stdin) = (p.stdout, p.stdin)
346
347The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
348except that:
349
350* subprocess.Popen raises an exception if the execution fails
351* the capturestderr argument is replaced with the stderr argument.
352* stdin=PIPE and stdout=PIPE must be specified.
353* popen2 closes all filedescriptors by default, but you have to specify
Tim Peterse718f612004-10-12 21:51:32 +0000354 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000355
356
357"""
358
359import sys
360mswindows = (sys.platform == "win32")
361
362import os
363import types
364import traceback
365
366if mswindows:
367 import threading
368 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000369 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000371 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
372 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
373 from win32api import GetCurrentProcess, DuplicateHandle, \
374 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000375 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000377 from win32process import CreateProcess, STARTUPINFO, \
378 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000379 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000381 else:
382 from _subprocess import *
383 class STARTUPINFO:
384 dwFlags = 0
385 hStdInput = None
386 hStdOutput = None
387 hStdError = None
388 class pywintypes:
389 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390else:
391 import select
392 import errno
393 import fcntl
394 import pickle
395
396__all__ = ["Popen", "PIPE", "STDOUT", "call"]
397
398try:
399 MAXFD = os.sysconf("SC_OPEN_MAX")
400except:
401 MAXFD = 256
402
403# True/False does not exist on 2.2.0
404try:
405 False
406except NameError:
407 False = 0
408 True = 1
409
410_active = []
411
412def _cleanup():
413 for inst in _active[:]:
414 inst.poll()
415
416PIPE = -1
417STDOUT = -2
418
419
Peter Astrand5f5e1412004-12-05 20:15:36 +0000420def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421 """Run command with arguments. Wait for command to complete, then
422 return the returncode attribute.
423
424 The arguments are the same as for the Popen constructor. Example:
425
426 retcode = call(["ls", "-l"])
427 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000428 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429
430
431def list2cmdline(seq):
432 """
433 Translate a sequence of arguments into a command line
434 string, using the same rules as the MS C runtime:
435
436 1) Arguments are delimited by white space, which is either a
437 space or a tab.
438
439 2) A string surrounded by double quotation marks is
440 interpreted as a single argument, regardless of white space
441 contained within. A quoted string can be embedded in an
442 argument.
443
444 3) A double quotation mark preceded by a backslash is
445 interpreted as a literal double quotation mark.
446
447 4) Backslashes are interpreted literally, unless they
448 immediately precede a double quotation mark.
449
450 5) If backslashes immediately precede a double quotation mark,
451 every pair of backslashes is interpreted as a literal
452 backslash. If the number of backslashes is odd, the last
453 backslash escapes the next double quotation mark as
454 described in rule 3.
455 """
456
457 # See
458 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
459 result = []
460 needquote = False
461 for arg in seq:
462 bs_buf = []
463
464 # Add a space to separate this argument from the others
465 if result:
466 result.append(' ')
467
468 needquote = (" " in arg) or ("\t" in arg)
469 if needquote:
470 result.append('"')
471
472 for c in arg:
473 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000474 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 bs_buf.append(c)
476 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000477 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 result.append('\\' * len(bs_buf)*2)
479 bs_buf = []
480 result.append('\\"')
481 else:
482 # Normal char
483 if bs_buf:
484 result.extend(bs_buf)
485 bs_buf = []
486 result.append(c)
487
Tim Peterse718f612004-10-12 21:51:32 +0000488 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 if bs_buf:
490 result.extend(bs_buf)
491
492 if needquote:
493 result.append('"')
494
495 return ''.join(result)
496
497
498class Popen(object):
499 def __init__(self, args, bufsize=0, executable=None,
500 stdin=None, stdout=None, stderr=None,
501 preexec_fn=None, close_fds=False, shell=False,
502 cwd=None, env=None, universal_newlines=False,
503 startupinfo=None, creationflags=0):
504 """Create new Popen instance."""
505 _cleanup()
506
Peter Astrand738131d2004-11-30 21:04:45 +0000507 if not isinstance(bufsize, (int, long)):
508 raise TypeError("bufsize must be an integer")
509
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000511 if preexec_fn is not None:
512 raise ValueError("preexec_fn is not supported on Windows "
513 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000515 raise ValueError("close_fds is not supported on Windows "
516 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 else:
518 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000519 if startupinfo is not None:
520 raise ValueError("startupinfo is only supported on Windows "
521 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000523 raise ValueError("creationflags is only supported on Windows "
524 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525
Tim Peterse718f612004-10-12 21:51:32 +0000526 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 self.stdout = None
528 self.stderr = None
529 self.pid = None
530 self.returncode = None
531 self.universal_newlines = universal_newlines
532
533 # Input and output objects. The general principle is like
534 # this:
535 #
536 # Parent Child
537 # ------ -----
538 # p2cwrite ---stdin---> p2cread
539 # c2pread <--stdout--- c2pwrite
540 # errread <--stderr--- errwrite
541 #
542 # On POSIX, the child objects are file descriptors. On
543 # Windows, these are Windows file handles. The parent objects
544 # are file descriptors on both platforms. The parent objects
545 # are None when not using PIPEs. The child objects are None
546 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000547
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 (p2cread, p2cwrite,
549 c2pread, c2pwrite,
550 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
551
552 self._execute_child(args, executable, preexec_fn, close_fds,
553 cwd, env, universal_newlines,
554 startupinfo, creationflags, shell,
555 p2cread, p2cwrite,
556 c2pread, c2pwrite,
557 errread, errwrite)
558
559 if p2cwrite:
560 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
561 if c2pread:
562 if universal_newlines:
563 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
564 else:
565 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
566 if errread:
567 if universal_newlines:
568 self.stderr = os.fdopen(errread, 'rU', bufsize)
569 else:
570 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000571
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572 _active.append(self)
573
574
575 def _translate_newlines(self, data):
576 data = data.replace("\r\n", "\n")
577 data = data.replace("\r", "\n")
578 return data
579
580
581 if mswindows:
582 #
583 # Windows methods
584 #
585 def _get_handles(self, stdin, stdout, stderr):
586 """Construct and return tupel with IO objects:
587 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
588 """
589 if stdin == None and stdout == None and stderr == None:
590 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000591
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 p2cread, p2cwrite = None, None
593 c2pread, c2pwrite = None, None
594 errread, errwrite = None, None
595
596 if stdin == None:
597 p2cread = GetStdHandle(STD_INPUT_HANDLE)
598 elif stdin == PIPE:
599 p2cread, p2cwrite = CreatePipe(None, 0)
600 # Detach and turn into fd
601 p2cwrite = p2cwrite.Detach()
602 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
603 elif type(stdin) == types.IntType:
604 p2cread = msvcrt.get_osfhandle(stdin)
605 else:
606 # Assuming file-like object
607 p2cread = msvcrt.get_osfhandle(stdin.fileno())
608 p2cread = self._make_inheritable(p2cread)
609
610 if stdout == None:
611 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
612 elif stdout == PIPE:
613 c2pread, c2pwrite = CreatePipe(None, 0)
614 # Detach and turn into fd
615 c2pread = c2pread.Detach()
616 c2pread = msvcrt.open_osfhandle(c2pread, 0)
617 elif type(stdout) == types.IntType:
618 c2pwrite = msvcrt.get_osfhandle(stdout)
619 else:
620 # Assuming file-like object
621 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
622 c2pwrite = self._make_inheritable(c2pwrite)
623
624 if stderr == None:
625 errwrite = GetStdHandle(STD_ERROR_HANDLE)
626 elif stderr == PIPE:
627 errread, errwrite = CreatePipe(None, 0)
628 # Detach and turn into fd
629 errread = errread.Detach()
630 errread = msvcrt.open_osfhandle(errread, 0)
631 elif stderr == STDOUT:
632 errwrite = c2pwrite
633 elif type(stderr) == types.IntType:
634 errwrite = msvcrt.get_osfhandle(stderr)
635 else:
636 # Assuming file-like object
637 errwrite = msvcrt.get_osfhandle(stderr.fileno())
638 errwrite = self._make_inheritable(errwrite)
639
640 return (p2cread, p2cwrite,
641 c2pread, c2pwrite,
642 errread, errwrite)
643
644
645 def _make_inheritable(self, handle):
646 """Return a duplicate of handle, which is inheritable"""
647 return DuplicateHandle(GetCurrentProcess(), handle,
648 GetCurrentProcess(), 0, 1,
649 DUPLICATE_SAME_ACCESS)
650
651
652 def _find_w9xpopen(self):
653 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000654 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
655 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 if not os.path.exists(w9xpopen):
657 # Eeek - file-not-found - possibly an embedding
658 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000659 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
660 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000662 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
663 "needed for Popen to work with your "
664 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 return w9xpopen
666
Tim Peterse718f612004-10-12 21:51:32 +0000667
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 def _execute_child(self, args, executable, preexec_fn, close_fds,
669 cwd, env, universal_newlines,
670 startupinfo, creationflags, shell,
671 p2cread, p2cwrite,
672 c2pread, c2pwrite,
673 errread, errwrite):
674 """Execute program (MS Windows version)"""
675
676 if not isinstance(args, types.StringTypes):
677 args = list2cmdline(args)
678
Peter Astrandc1d65362004-11-07 14:30:34 +0000679 # Process startup details
680 default_startupinfo = STARTUPINFO()
681 if startupinfo == None:
682 startupinfo = default_startupinfo
683 if not None in (p2cread, c2pwrite, errwrite):
684 startupinfo.dwFlags |= STARTF_USESTDHANDLES
685 startupinfo.hStdInput = p2cread
686 startupinfo.hStdOutput = c2pwrite
687 startupinfo.hStdError = errwrite
688
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000690 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
691 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000692 comspec = os.environ.get("COMSPEC", "cmd.exe")
693 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000694 if (GetVersion() >= 0x80000000L or
695 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000696 # Win9x, or using command.com on NT. We need to
697 # use the w9xpopen intermediate program. For more
698 # information, see KB Q150956
699 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
700 w9xpopen = self._find_w9xpopen()
701 args = '"%s" %s' % (w9xpopen, args)
702 # Not passing CREATE_NEW_CONSOLE has been known to
703 # cause random failures on win9x. Specifically a
704 # dialog: "Your program accessed mem currently in
705 # use at xxx" and a hopeful warning about the
706 # stability of your system. Cost is Ctrl+C wont
707 # kill children.
708 creationflags |= CREATE_NEW_CONSOLE
709
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 # Start the process
711 try:
712 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000713 # no special security
714 None, None,
715 # must inherit handles to pass std
716 # handles
717 1,
718 creationflags,
719 env,
720 cwd,
721 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 except pywintypes.error, e:
723 # Translate pywintypes.error to WindowsError, which is
724 # a subclass of OSError. FIXME: We should really
725 # translate errno using _sys_errlist (or simliar), but
726 # how can this be done from Python?
727 raise WindowsError(*e.args)
728
729 # Retain the process handle, but close the thread handle
730 self._handle = hp
731 self.pid = pid
732 ht.Close()
733
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000734 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735 # handles that only the child should have open. You need
736 # to make sure that no handles to the write end of the
737 # output pipe are maintained in this process or else the
738 # pipe will not close when the child process exits and the
739 # ReadFile will hang.
740 if p2cread != None:
741 p2cread.Close()
742 if c2pwrite != None:
743 c2pwrite.Close()
744 if errwrite != None:
745 errwrite.Close()
746
Tim Peterse718f612004-10-12 21:51:32 +0000747
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 def poll(self):
749 """Check if child process has terminated. Returns returncode
750 attribute."""
751 if self.returncode == None:
752 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
753 self.returncode = GetExitCodeProcess(self._handle)
754 _active.remove(self)
755 return self.returncode
756
757
758 def wait(self):
759 """Wait for child process to terminate. Returns returncode
760 attribute."""
761 if self.returncode == None:
762 obj = WaitForSingleObject(self._handle, INFINITE)
763 self.returncode = GetExitCodeProcess(self._handle)
764 _active.remove(self)
765 return self.returncode
766
767
768 def _readerthread(self, fh, buffer):
769 buffer.append(fh.read())
770
771
772 def communicate(self, input=None):
773 """Interact with process: Send data to stdin. Read data from
774 stdout and stderr, until end-of-file is reached. Wait for
775 process to terminate. The optional input argument should be a
776 string to be sent to the child process, or None, if no data
777 should be sent to the child.
778
779 communicate() returns a tuple (stdout, stderr)."""
780 stdout = None # Return
781 stderr = None # Return
782
783 if self.stdout:
784 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000785 stdout_thread = threading.Thread(target=self._readerthread,
786 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 stdout_thread.setDaemon(True)
788 stdout_thread.start()
789 if self.stderr:
790 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000791 stderr_thread = threading.Thread(target=self._readerthread,
792 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000793 stderr_thread.setDaemon(True)
794 stderr_thread.start()
795
796 if self.stdin:
797 if input != None:
798 self.stdin.write(input)
799 self.stdin.close()
800
801 if self.stdout:
802 stdout_thread.join()
803 if self.stderr:
804 stderr_thread.join()
805
806 # All data exchanged. Translate lists into strings.
807 if stdout != None:
808 stdout = stdout[0]
809 if stderr != None:
810 stderr = stderr[0]
811
812 # Translate newlines, if requested. We cannot let the file
813 # object do the translation: It is based on stdio, which is
814 # impossible to combine with select (unless forcing no
815 # buffering).
816 if self.universal_newlines and hasattr(open, 'newlines'):
817 if stdout:
818 stdout = self._translate_newlines(stdout)
819 if stderr:
820 stderr = self._translate_newlines(stderr)
821
822 self.wait()
823 return (stdout, stderr)
824
825 else:
826 #
827 # POSIX methods
828 #
829 def _get_handles(self, stdin, stdout, stderr):
830 """Construct and return tupel with IO objects:
831 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
832 """
833 p2cread, p2cwrite = None, None
834 c2pread, c2pwrite = None, None
835 errread, errwrite = None, None
836
837 if stdin == None:
838 pass
839 elif stdin == PIPE:
840 p2cread, p2cwrite = os.pipe()
841 elif type(stdin) == types.IntType:
842 p2cread = stdin
843 else:
844 # Assuming file-like object
845 p2cread = stdin.fileno()
846
847 if stdout == None:
848 pass
849 elif stdout == PIPE:
850 c2pread, c2pwrite = os.pipe()
851 elif type(stdout) == types.IntType:
852 c2pwrite = stdout
853 else:
854 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000855 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856
857 if stderr == None:
858 pass
859 elif stderr == PIPE:
860 errread, errwrite = os.pipe()
861 elif stderr == STDOUT:
862 errwrite = c2pwrite
863 elif type(stderr) == types.IntType:
864 errwrite = stderr
865 else:
866 # Assuming file-like object
867 errwrite = stderr.fileno()
868
869 return (p2cread, p2cwrite,
870 c2pread, c2pwrite,
871 errread, errwrite)
872
873
874 def _set_cloexec_flag(self, fd):
875 try:
876 cloexec_flag = fcntl.FD_CLOEXEC
877 except AttributeError:
878 cloexec_flag = 1
879
880 old = fcntl.fcntl(fd, fcntl.F_GETFD)
881 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
882
883
884 def _close_fds(self, but):
885 for i in range(3, MAXFD):
886 if i == but:
887 continue
888 try:
889 os.close(i)
890 except:
891 pass
Tim Peterse718f612004-10-12 21:51:32 +0000892
893
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894 def _execute_child(self, args, executable, preexec_fn, close_fds,
895 cwd, env, universal_newlines,
896 startupinfo, creationflags, shell,
897 p2cread, p2cwrite,
898 c2pread, c2pwrite,
899 errread, errwrite):
900 """Execute program (POSIX version)"""
901
902 if isinstance(args, types.StringTypes):
903 args = [args]
904
905 if shell:
906 args = ["/bin/sh", "-c"] + args
907
908 if executable == None:
909 executable = args[0]
910
911 # For transferring possible exec failure from child to parent
912 # The first char specifies the exception type: 0 means
913 # OSError, 1 means some other error.
914 errpipe_read, errpipe_write = os.pipe()
915 self._set_cloexec_flag(errpipe_write)
916
917 self.pid = os.fork()
918 if self.pid == 0:
919 # Child
920 try:
921 # Close parent's pipe ends
922 if p2cwrite:
923 os.close(p2cwrite)
924 if c2pread:
925 os.close(c2pread)
926 if errread:
927 os.close(errread)
928 os.close(errpipe_read)
929
930 # Dup fds for child
931 if p2cread:
932 os.dup2(p2cread, 0)
933 if c2pwrite:
934 os.dup2(c2pwrite, 1)
935 if errwrite:
936 os.dup2(errwrite, 2)
937
938 # Close pipe fds. Make sure we doesn't close the same
939 # fd more than once.
940 if p2cread:
941 os.close(p2cread)
942 if c2pwrite and c2pwrite not in (p2cread,):
943 os.close(c2pwrite)
944 if errwrite and errwrite not in (p2cread, c2pwrite):
945 os.close(errwrite)
946
947 # Close all other fds, if asked for
948 if close_fds:
949 self._close_fds(but=errpipe_write)
950
951 if cwd != None:
952 os.chdir(cwd)
953
954 if preexec_fn:
955 apply(preexec_fn)
956
957 if env == None:
958 os.execvp(executable, args)
959 else:
960 os.execvpe(executable, args, env)
961
962 except:
963 exc_type, exc_value, tb = sys.exc_info()
964 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +0000965 exc_lines = traceback.format_exception(exc_type,
966 exc_value,
967 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968 exc_value.child_traceback = ''.join(exc_lines)
969 os.write(errpipe_write, pickle.dumps(exc_value))
970
971 # This exitcode won't be reported to applications, so it
972 # really doesn't matter what we return.
973 os._exit(255)
974
975 # Parent
976 os.close(errpipe_write)
977 if p2cread and p2cwrite:
978 os.close(p2cread)
979 if c2pwrite and c2pread:
980 os.close(c2pwrite)
981 if errwrite and errread:
982 os.close(errwrite)
983
984 # Wait for exec to fail or succeed; possibly raising exception
985 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
986 os.close(errpipe_read)
987 if data != "":
988 child_exception = pickle.loads(data)
989 raise child_exception
990
991
992 def _handle_exitstatus(self, sts):
993 if os.WIFSIGNALED(sts):
994 self.returncode = -os.WTERMSIG(sts)
995 elif os.WIFEXITED(sts):
996 self.returncode = os.WEXITSTATUS(sts)
997 else:
998 # Should never happen
999 raise RuntimeError("Unknown child exit status!")
1000
1001 _active.remove(self)
1002
Tim Peterse718f612004-10-12 21:51:32 +00001003
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001004 def poll(self):
1005 """Check if child process has terminated. Returns returncode
1006 attribute."""
1007 if self.returncode == None:
1008 try:
1009 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1010 if pid == self.pid:
1011 self._handle_exitstatus(sts)
1012 except os.error:
1013 pass
1014 return self.returncode
1015
1016
1017 def wait(self):
1018 """Wait for child process to terminate. Returns returncode
1019 attribute."""
1020 if self.returncode == None:
1021 pid, sts = os.waitpid(self.pid, 0)
1022 self._handle_exitstatus(sts)
1023 return self.returncode
1024
1025
1026 def communicate(self, input=None):
1027 """Interact with process: Send data to stdin. Read data from
1028 stdout and stderr, until end-of-file is reached. Wait for
1029 process to terminate. The optional input argument should be a
1030 string to be sent to the child process, or None, if no data
1031 should be sent to the child.
1032
1033 communicate() returns a tuple (stdout, stderr)."""
1034 read_set = []
1035 write_set = []
1036 stdout = None # Return
1037 stderr = None # Return
1038
1039 if self.stdin:
1040 # Flush stdio buffer. This might block, if the user has
1041 # been writing to .stdin in an uncontrolled fashion.
1042 self.stdin.flush()
1043 if input:
1044 write_set.append(self.stdin)
1045 else:
1046 self.stdin.close()
1047 if self.stdout:
1048 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001049 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001050 if self.stderr:
1051 read_set.append(self.stderr)
1052 stderr = []
1053
1054 while read_set or write_set:
1055 rlist, wlist, xlist = select.select(read_set, write_set, [])
1056
1057 if self.stdin in wlist:
1058 # When select has indicated that the file is writable,
1059 # we can write up to PIPE_BUF bytes without risk
1060 # blocking. POSIX defines PIPE_BUF >= 512
1061 bytes_written = os.write(self.stdin.fileno(), input[:512])
1062 input = input[bytes_written:]
1063 if not input:
1064 self.stdin.close()
1065 write_set.remove(self.stdin)
1066
1067 if self.stdout in rlist:
1068 data = os.read(self.stdout.fileno(), 1024)
1069 if data == "":
1070 self.stdout.close()
1071 read_set.remove(self.stdout)
1072 stdout.append(data)
1073
1074 if self.stderr in rlist:
1075 data = os.read(self.stderr.fileno(), 1024)
1076 if data == "":
1077 self.stderr.close()
1078 read_set.remove(self.stderr)
1079 stderr.append(data)
1080
1081 # All data exchanged. Translate lists into strings.
1082 if stdout != None:
1083 stdout = ''.join(stdout)
1084 if stderr != None:
1085 stderr = ''.join(stderr)
1086
1087 # Translate newlines, if requested. We cannot let the file
1088 # object do the translation: It is based on stdio, which is
1089 # impossible to combine with select (unless forcing no
1090 # buffering).
1091 if self.universal_newlines and hasattr(open, 'newlines'):
1092 if stdout:
1093 stdout = self._translate_newlines(stdout)
1094 if stderr:
1095 stderr = self._translate_newlines(stderr)
1096
1097 self.wait()
1098 return (stdout, stderr)
1099
1100
1101def _demo_posix():
1102 #
1103 # Example 1: Simple redirection: Get process list
1104 #
1105 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1106 print "Process list:"
1107 print plist
1108
1109 #
1110 # Example 2: Change uid before executing child
1111 #
1112 if os.getuid() == 0:
1113 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1114 p.wait()
1115
1116 #
1117 # Example 3: Connecting several subprocesses
1118 #
1119 print "Looking for 'hda'..."
1120 p1 = Popen(["dmesg"], stdout=PIPE)
1121 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1122 print repr(p2.communicate()[0])
1123
1124 #
1125 # Example 4: Catch execution error
1126 #
1127 print
1128 print "Trying a weird file..."
1129 try:
1130 print Popen(["/this/path/does/not/exist"]).communicate()
1131 except OSError, e:
1132 if e.errno == errno.ENOENT:
1133 print "The file didn't exist. I thought so..."
1134 print "Child traceback:"
1135 print e.child_traceback
1136 else:
1137 print "Error", e.errno
1138 else:
1139 print >>sys.stderr, "Gosh. No error."
1140
1141
1142def _demo_windows():
1143 #
1144 # Example 1: Connecting several subprocesses
1145 #
1146 print "Looking for 'PROMPT' in set output..."
1147 p1 = Popen("set", stdout=PIPE, shell=True)
1148 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1149 print repr(p2.communicate()[0])
1150
1151 #
1152 # Example 2: Simple execution of program
1153 #
1154 print "Executing calc..."
1155 p = Popen("calc")
1156 p.wait()
1157
1158
1159if __name__ == "__main__":
1160 if mswindows:
1161 _demo_windows()
1162 else:
1163 _demo_posix()