blob: 355529eb58945eeb7165fc27d9d245eea7adebc5 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001# subprocess - Subprocesses with accessible I/O streams
2#
3# For more information about this module, see PEP 324.
4#
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
28"""subprocess - Subprocesses with accessible I/O streams
29
30This module allows you to spawn processes and connect to their
31input/output/error pipes and obtain their return codes under Unix.
32This module intends to replace several other, older modules and
33functions, like:
34
35os.system
36os.spawn*
37os.popen*
38popen2.*
39commands.*
40
41Information about how the subprocess module can be used to replace these
42modules and functions can be found below.
43
44
45
46Using the subprocess module
47===========================
48This module defines one class called Popen:
49
50class Popen(args, bufsize=0, executable=None,
51 stdin=None, stdout=None, stderr=None,
52 preexec_fn=None, close_fds=False, shell=False,
53 cwd=None, env=None, universal_newlines=False,
54 startupinfo=None, creationflags=0):
55
56
57Arguments are:
58
59args should be a string, or a sequence of program arguments. The
60program to execute is normally the first item in the args sequence or
61string, but can be explicitly set by using the executable argument.
62
63On UNIX, with shell=False (default): In this case, the Popen class
64uses os.execvp() to execute the child program. args should normally
65be a sequence. A string will be treated as a sequence with the string
66as the only item (the program to execute).
67
68On UNIX, with shell=True: If args is a string, it specifies the
69command string to execute through the shell. If args is a sequence,
70the first item specifies the command string, and any additional items
71will be treated as additional shell arguments.
72
73On Windows: the Popen class uses CreateProcess() to execute the child
74program, which operates on strings. If args is a sequence, it will be
75converted to a string using the list2cmdline method. Please note that
76not all MS Windows applications interpret the command line the same
77way: The list2cmdline is designed for applications using the same
78rules as the MS C runtime.
79
80bufsize, if given, has the same meaning as the corresponding argument
81to the built-in open() function: 0 means unbuffered, 1 means line
82buffered, any other positive value means use a buffer of
83(approximately) that size. A negative bufsize means to use the system
84default, which usually means fully buffered. The default value for
85bufsize is 0 (unbuffered).
86
87stdin, stdout and stderr specify the executed programs' standard
88input, standard output and standard error file handles, respectively.
89Valid values are PIPE, an existing file descriptor (a positive
90integer), an existing file object, and None. PIPE indicates that a
91new pipe to the child should be created. With None, no redirection
92will occur; the child's file handles will be inherited from the
93parent. Additionally, stderr can be STDOUT, which indicates that the
94stderr data from the applications should be captured into the same
95file handle as for stdout.
96
97If preexec_fn is set to a callable object, this object will be called
98in the child process just before the child is executed.
99
100If close_fds is true, all file descriptors except 0, 1 and 2 will be
101closed before the child process is executed.
102
103if shell is true, the specified command will be executed through the
104shell.
105
106If cwd is not None, the current directory will be changed to cwd
107before the child is executed.
108
109If env is not None, it defines the environment variables for the new
110process.
111
112If universal_newlines is true, the file objects stdout and stderr are
113opened as a text files, but lines may be terminated by any of '\n',
114the Unix end-of-line convention, '\r', the Macintosh convention or
115'\r\n', the Windows convention. All of these external representations
116are seen as '\n' by the Python program. Note: This feature is only
117available if Python is built with universal newline support (the
118default). Also, the newlines attribute of the file objects stdout,
119stdin and stderr are not updated by the communicate() method.
120
121The startupinfo and creationflags, if given, will be passed to the
122underlying CreateProcess() function. They can specify things such as
123appearance of the main window and priority for the new process.
124(Windows only)
125
126
127This module also defines two shortcut functions:
128
129call(*args, **kwargs):
130 Run command with arguments. Wait for command to complete, then
131 return the returncode attribute.
132
133 The arguments are the same as for the Popen constructor. Example:
134
135 retcode = call(["ls", "-l"])
136
137
138Exceptions
139----------
140Exceptions raised in the child process, before the new program has
141started to execute, will be re-raised in the parent. Additionally,
142the exception object will have one extra attribute called
143'child_traceback', which is a string containing traceback information
144from the childs point of view.
145
146The most common exception raised is OSError. This occurs, for
147example, when trying to execute a non-existent file. Applications
148should prepare for OSErrors.
149
150A ValueError will be raised if Popen is called with invalid arguments.
151
152
153Security
154--------
155Unlike some other popen functions, this implementation will never call
156/bin/sh implicitly. This means that all characters, including shell
157metacharacters, can safely be passed to child processes.
158
159
160Popen objects
161=============
162Instances of the Popen class have the following methods:
163
164poll()
165 Check if child process has terminated. Returns returncode
166 attribute.
167
168wait()
169 Wait for child process to terminate. Returns returncode attribute.
170
171communicate(input=None)
172 Interact with process: Send data to stdin. Read data from stdout
173 and stderr, until end-of-file is reached. Wait for process to
174 terminate. The optional stdin argument should be a string to be
175 sent to the child process, or None, if no data should be sent to
176 the child.
177
178 communicate() returns a tuple (stdout, stderr).
179
180 Note: The data read is buffered in memory, so do not use this
181 method if the data size is large or unlimited.
182
183The following attributes are also available:
184
185stdin
186 If the stdin argument is PIPE, this attribute is a file object
187 that provides input to the child process. Otherwise, it is None.
188
189stdout
190 If the stdout argument is PIPE, this attribute is a file object
191 that provides output from the child process. Otherwise, it is
192 None.
193
194stderr
195 If the stderr argument is PIPE, this attribute is file object that
196 provides error output from the child process. Otherwise, it is
197 None.
198
199pid
200 The process ID of the child process.
201
202returncode
203 The child return code. A None value indicates that the process
204 hasn't terminated yet. A negative value -N indicates that the
205 child was terminated by signal N (UNIX only).
206
207
208Replacing older functions with the subprocess module
209====================================================
210In this section, "a ==> b" means that b can be used as a replacement
211for a.
212
213Note: All functions in this section fail (more or less) silently if
214the executed program cannot be found; this module raises an OSError
215exception.
216
217In the following examples, we assume that the subprocess module is
218imported with "from subprocess import *".
219
220
221Replacing /bin/sh shell backquote
222---------------------------------
223output=`mycmd myarg`
224==>
225output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
226
227
228Replacing shell pipe line
229-------------------------
230output=`dmesg | grep hda`
231==>
232p1 = Popen(["dmesg"], stdout=PIPE)
233p2 = Popen(["grep", "hda"], stdin=p1.stdout)
234output = p2.communicate()[0]
235
236
237Replacing os.system()
238---------------------
239sts = os.system("mycmd" + " myarg")
240==>
241p = Popen("mycmd" + " myarg", shell=True)
242sts = os.waitpid(p.pid, 0)
243
244Note:
245
246* Calling the program through the shell is usually not required.
247
248* It's easier to look at the returncode attribute than the
249 exitstatus.
250
251A more real-world example would look like this:
252
253try:
254 retcode = call("mycmd" + " myarg", shell=True)
255 if retcode < 0:
256 print >>sys.stderr, "Child was terminated by signal", -retcode
257 else:
258 print >>sys.stderr, "Child returned", retcode
259except OSError, e:
260 print >>sys.stderr, "Execution failed:", e
261
262
263Replacing os.spawn*
264-------------------
265P_NOWAIT example:
266
267pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
268==>
269pid = Popen(["/bin/mycmd", "myarg"]).pid
270
271
272P_WAIT example:
273
274retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
275==>
276retcode = call(["/bin/mycmd", "myarg"])
277
278
279Vector example:
280
281os.spawnvp(os.P_NOWAIT, path, args)
282==>
283Popen([path] + args[1:])
284
285
286Environment example:
287
288os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
289==>
290Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
291
292
293Replacing os.popen*
294-------------------
295pipe = os.popen(cmd, mode='r', bufsize)
296==>
297pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
298
299pipe = os.popen(cmd, mode='w', bufsize)
300==>
301pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
302
303
304(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
305==>
306p = Popen(cmd, shell=True, bufsize=bufsize,
307 stdin=PIPE, stdout=PIPE, close_fds=True)
308(child_stdin, child_stdout) = (p.stdin, p.stdout)
309
310
311(child_stdin,
312 child_stdout,
313 child_stderr) = os.popen3(cmd, mode, bufsize)
314==>
315p = Popen(cmd, shell=True, bufsize=bufsize,
316 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
317(child_stdin,
318 child_stdout,
319 child_stderr) = (p.stdin, p.stdout, p.stderr)
320
321
322(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
323==>
324p = Popen(cmd, shell=True, bufsize=bufsize,
325 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
326(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
327
328
329Replacing popen2.*
330------------------
331Note: If the cmd argument to popen2 functions is a string, the command
332is executed through /bin/sh. If it is a list, the command is directly
333executed.
334
335(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
336==>
337p = Popen(["somestring"], shell=True, bufsize=bufsize
338 stdin=PIPE, stdout=PIPE, close_fds=True)
339(child_stdout, child_stdin) = (p.stdout, p.stdin)
340
341
342(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
343==>
344p = Popen(["mycmd", "myarg"], bufsize=bufsize,
345 stdin=PIPE, stdout=PIPE, close_fds=True)
346(child_stdout, child_stdin) = (p.stdout, p.stdin)
347
348The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
349except that:
350
351* subprocess.Popen raises an exception if the execution fails
352* the capturestderr argument is replaced with the stderr argument.
353* stdin=PIPE and stdout=PIPE must be specified.
354* popen2 closes all filedescriptors by default, but you have to specify
355 close_fds=True with subprocess.Popen.
356
357
358"""
359
360import sys
361mswindows = (sys.platform == "win32")
362
363import os
364import types
365import traceback
366
367if mswindows:
368 import threading
369 import msvcrt
370 try:
371 from _subprocess import *
372 class STARTUPINFO:
373 dwFlags = 0
374 hStdInput = None
375 hStdOutput = None
376 hStdError = None
377 class pywintypes:
378 error = IOError
379 except ImportError:
380 import pywintypes
381 from win32api import GetStdHandle, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
382 from win32api import GetCurrentProcess, DuplicateHandle, GetModuleFileName, GetVersion
383 from win32con import DUPLICATE_SAME_ACCESS
384 from win32pipe import CreatePipe
385 from win32process import CreateProcess, STARTUPINFO, GetExitCodeProcess, STARTF_USESTDHANDLES, CREATE_NEW_CONSOLE
386 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
387else:
388 import select
389 import errno
390 import fcntl
391 import pickle
392
393__all__ = ["Popen", "PIPE", "STDOUT", "call"]
394
395try:
396 MAXFD = os.sysconf("SC_OPEN_MAX")
397except:
398 MAXFD = 256
399
400# True/False does not exist on 2.2.0
401try:
402 False
403except NameError:
404 False = 0
405 True = 1
406
407_active = []
408
409def _cleanup():
410 for inst in _active[:]:
411 inst.poll()
412
413PIPE = -1
414STDOUT = -2
415
416
417def call(*args, **kwargs):
418 """Run command with arguments. Wait for command to complete, then
419 return the returncode attribute.
420
421 The arguments are the same as for the Popen constructor. Example:
422
423 retcode = call(["ls", "-l"])
424 """
425 return Popen(*args, **kwargs).wait()
426
427
428def list2cmdline(seq):
429 """
430 Translate a sequence of arguments into a command line
431 string, using the same rules as the MS C runtime:
432
433 1) Arguments are delimited by white space, which is either a
434 space or a tab.
435
436 2) A string surrounded by double quotation marks is
437 interpreted as a single argument, regardless of white space
438 contained within. A quoted string can be embedded in an
439 argument.
440
441 3) A double quotation mark preceded by a backslash is
442 interpreted as a literal double quotation mark.
443
444 4) Backslashes are interpreted literally, unless they
445 immediately precede a double quotation mark.
446
447 5) If backslashes immediately precede a double quotation mark,
448 every pair of backslashes is interpreted as a literal
449 backslash. If the number of backslashes is odd, the last
450 backslash escapes the next double quotation mark as
451 described in rule 3.
452 """
453
454 # See
455 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
456 result = []
457 needquote = False
458 for arg in seq:
459 bs_buf = []
460
461 # Add a space to separate this argument from the others
462 if result:
463 result.append(' ')
464
465 needquote = (" " in arg) or ("\t" in arg)
466 if needquote:
467 result.append('"')
468
469 for c in arg:
470 if c == '\\':
471 # Don't know if we need to double yet.
472 bs_buf.append(c)
473 elif c == '"':
474 # Double backspaces.
475 result.append('\\' * len(bs_buf)*2)
476 bs_buf = []
477 result.append('\\"')
478 else:
479 # Normal char
480 if bs_buf:
481 result.extend(bs_buf)
482 bs_buf = []
483 result.append(c)
484
485 # Add remaining backspaces, if any.
486 if bs_buf:
487 result.extend(bs_buf)
488
489 if needquote:
490 result.append('"')
491
492 return ''.join(result)
493
494
495class Popen(object):
496 def __init__(self, args, bufsize=0, executable=None,
497 stdin=None, stdout=None, stderr=None,
498 preexec_fn=None, close_fds=False, shell=False,
499 cwd=None, env=None, universal_newlines=False,
500 startupinfo=None, creationflags=0):
501 """Create new Popen instance."""
502 _cleanup()
503
504 if mswindows:
505 if preexec_fn != None:
506 raise ValueError("preexec_fn is not supported on Windows platforms")
507 if close_fds:
508 raise ValueError("close_fds is not supported on Windows platforms")
509 else:
510 # POSIX
511 if startupinfo != None:
512 raise ValueError("startupinfo is only supported on Windows platforms")
513 if creationflags != 0:
514 raise ValueError("creationflags is only supported on Windows platforms")
515
516 self.stdin = None
517 self.stdout = None
518 self.stderr = None
519 self.pid = None
520 self.returncode = None
521 self.universal_newlines = universal_newlines
522
523 # Input and output objects. The general principle is like
524 # this:
525 #
526 # Parent Child
527 # ------ -----
528 # p2cwrite ---stdin---> p2cread
529 # c2pread <--stdout--- c2pwrite
530 # errread <--stderr--- errwrite
531 #
532 # On POSIX, the child objects are file descriptors. On
533 # Windows, these are Windows file handles. The parent objects
534 # are file descriptors on both platforms. The parent objects
535 # are None when not using PIPEs. The child objects are None
536 # when not redirecting.
537
538 (p2cread, p2cwrite,
539 c2pread, c2pwrite,
540 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
541
542 self._execute_child(args, executable, preexec_fn, close_fds,
543 cwd, env, universal_newlines,
544 startupinfo, creationflags, shell,
545 p2cread, p2cwrite,
546 c2pread, c2pwrite,
547 errread, errwrite)
548
549 if p2cwrite:
550 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
551 if c2pread:
552 if universal_newlines:
553 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
554 else:
555 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
556 if errread:
557 if universal_newlines:
558 self.stderr = os.fdopen(errread, 'rU', bufsize)
559 else:
560 self.stderr = os.fdopen(errread, 'rb', bufsize)
561
562 _active.append(self)
563
564
565 def _translate_newlines(self, data):
566 data = data.replace("\r\n", "\n")
567 data = data.replace("\r", "\n")
568 return data
569
570
571 if mswindows:
572 #
573 # Windows methods
574 #
575 def _get_handles(self, stdin, stdout, stderr):
576 """Construct and return tupel with IO objects:
577 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
578 """
579 if stdin == None and stdout == None and stderr == None:
580 return (None, None, None, None, None, None)
581
582 p2cread, p2cwrite = None, None
583 c2pread, c2pwrite = None, None
584 errread, errwrite = None, None
585
586 if stdin == None:
587 p2cread = GetStdHandle(STD_INPUT_HANDLE)
588 elif stdin == PIPE:
589 p2cread, p2cwrite = CreatePipe(None, 0)
590 # Detach and turn into fd
591 p2cwrite = p2cwrite.Detach()
592 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
593 elif type(stdin) == types.IntType:
594 p2cread = msvcrt.get_osfhandle(stdin)
595 else:
596 # Assuming file-like object
597 p2cread = msvcrt.get_osfhandle(stdin.fileno())
598 p2cread = self._make_inheritable(p2cread)
599
600 if stdout == None:
601 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
602 elif stdout == PIPE:
603 c2pread, c2pwrite = CreatePipe(None, 0)
604 # Detach and turn into fd
605 c2pread = c2pread.Detach()
606 c2pread = msvcrt.open_osfhandle(c2pread, 0)
607 elif type(stdout) == types.IntType:
608 c2pwrite = msvcrt.get_osfhandle(stdout)
609 else:
610 # Assuming file-like object
611 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
612 c2pwrite = self._make_inheritable(c2pwrite)
613
614 if stderr == None:
615 errwrite = GetStdHandle(STD_ERROR_HANDLE)
616 elif stderr == PIPE:
617 errread, errwrite = CreatePipe(None, 0)
618 # Detach and turn into fd
619 errread = errread.Detach()
620 errread = msvcrt.open_osfhandle(errread, 0)
621 elif stderr == STDOUT:
622 errwrite = c2pwrite
623 elif type(stderr) == types.IntType:
624 errwrite = msvcrt.get_osfhandle(stderr)
625 else:
626 # Assuming file-like object
627 errwrite = msvcrt.get_osfhandle(stderr.fileno())
628 errwrite = self._make_inheritable(errwrite)
629
630 return (p2cread, p2cwrite,
631 c2pread, c2pwrite,
632 errread, errwrite)
633
634
635 def _make_inheritable(self, handle):
636 """Return a duplicate of handle, which is inheritable"""
637 return DuplicateHandle(GetCurrentProcess(), handle,
638 GetCurrentProcess(), 0, 1,
639 DUPLICATE_SAME_ACCESS)
640
641
642 def _find_w9xpopen(self):
643 """Find and return absolut path to w9xpopen.exe"""
644 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe")
645 if not os.path.exists(w9xpopen):
646 # Eeek - file-not-found - possibly an embedding
647 # situation - see if we can locate it in sys.exec_prefix
648 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe")
649 if not os.path.exists(w9xpopen):
650 raise RuntimeError("Cannot locate w9xpopen.exe, which is needed "
651 "for Popen to work with your shell or platform.")
652 return w9xpopen
653
654
655 def _execute_child(self, args, executable, preexec_fn, close_fds,
656 cwd, env, universal_newlines,
657 startupinfo, creationflags, shell,
658 p2cread, p2cwrite,
659 c2pread, c2pwrite,
660 errread, errwrite):
661 """Execute program (MS Windows version)"""
662
663 if not isinstance(args, types.StringTypes):
664 args = list2cmdline(args)
665
666 if shell:
667 comspec = os.environ.get("COMSPEC", "cmd.exe")
668 args = comspec + " /c " + args
669 if GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == "command.com":
670 # Win9x, or using command.com on NT. We need to
671 # use the w9xpopen intermediate program. For more
672 # information, see KB Q150956
673 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
674 w9xpopen = self._find_w9xpopen()
675 args = '"%s" %s' % (w9xpopen, args)
676 # Not passing CREATE_NEW_CONSOLE has been known to
677 # cause random failures on win9x. Specifically a
678 # dialog: "Your program accessed mem currently in
679 # use at xxx" and a hopeful warning about the
680 # stability of your system. Cost is Ctrl+C wont
681 # kill children.
682 creationflags |= CREATE_NEW_CONSOLE
683
684 # Process startup details
685 if startupinfo == None:
686 startupinfo = STARTUPINFO()
687 if not None in (p2cread, c2pwrite, errwrite):
688 startupinfo.dwFlags |= STARTF_USESTDHANDLES
689 startupinfo.hStdInput = p2cread
690 startupinfo.hStdOutput = c2pwrite
691 startupinfo.hStdError = errwrite
692
693 # Start the process
694 try:
695 hp, ht, pid, tid = CreateProcess(executable, args,
696 None, None, # No special security
697 1, # Must inherit handles to pass std handles
698 creationflags,
699 env,
700 cwd,
701 startupinfo)
702 except pywintypes.error, e:
703 # Translate pywintypes.error to WindowsError, which is
704 # a subclass of OSError. FIXME: We should really
705 # translate errno using _sys_errlist (or simliar), but
706 # how can this be done from Python?
707 raise WindowsError(*e.args)
708
709 # Retain the process handle, but close the thread handle
710 self._handle = hp
711 self.pid = pid
712 ht.Close()
713
714 # Child is launched. Close the parents copy of those pipe
715 # handles that only the child should have open. You need
716 # to make sure that no handles to the write end of the
717 # output pipe are maintained in this process or else the
718 # pipe will not close when the child process exits and the
719 # ReadFile will hang.
720 if p2cread != None:
721 p2cread.Close()
722 if c2pwrite != None:
723 c2pwrite.Close()
724 if errwrite != None:
725 errwrite.Close()
726
727
728 def poll(self):
729 """Check if child process has terminated. Returns returncode
730 attribute."""
731 if self.returncode == None:
732 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
733 self.returncode = GetExitCodeProcess(self._handle)
734 _active.remove(self)
735 return self.returncode
736
737
738 def wait(self):
739 """Wait for child process to terminate. Returns returncode
740 attribute."""
741 if self.returncode == None:
742 obj = WaitForSingleObject(self._handle, INFINITE)
743 self.returncode = GetExitCodeProcess(self._handle)
744 _active.remove(self)
745 return self.returncode
746
747
748 def _readerthread(self, fh, buffer):
749 buffer.append(fh.read())
750
751
752 def communicate(self, input=None):
753 """Interact with process: Send data to stdin. Read data from
754 stdout and stderr, until end-of-file is reached. Wait for
755 process to terminate. The optional input argument should be a
756 string to be sent to the child process, or None, if no data
757 should be sent to the child.
758
759 communicate() returns a tuple (stdout, stderr)."""
760 stdout = None # Return
761 stderr = None # Return
762
763 if self.stdout:
764 stdout = []
765 stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout,))
766 stdout_thread.setDaemon(True)
767 stdout_thread.start()
768 if self.stderr:
769 stderr = []
770 stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr,))
771 stderr_thread.setDaemon(True)
772 stderr_thread.start()
773
774 if self.stdin:
775 if input != None:
776 self.stdin.write(input)
777 self.stdin.close()
778
779 if self.stdout:
780 stdout_thread.join()
781 if self.stderr:
782 stderr_thread.join()
783
784 # All data exchanged. Translate lists into strings.
785 if stdout != None:
786 stdout = stdout[0]
787 if stderr != None:
788 stderr = stderr[0]
789
790 # Translate newlines, if requested. We cannot let the file
791 # object do the translation: It is based on stdio, which is
792 # impossible to combine with select (unless forcing no
793 # buffering).
794 if self.universal_newlines and hasattr(open, 'newlines'):
795 if stdout:
796 stdout = self._translate_newlines(stdout)
797 if stderr:
798 stderr = self._translate_newlines(stderr)
799
800 self.wait()
801 return (stdout, stderr)
802
803 else:
804 #
805 # POSIX methods
806 #
807 def _get_handles(self, stdin, stdout, stderr):
808 """Construct and return tupel with IO objects:
809 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
810 """
811 p2cread, p2cwrite = None, None
812 c2pread, c2pwrite = None, None
813 errread, errwrite = None, None
814
815 if stdin == None:
816 pass
817 elif stdin == PIPE:
818 p2cread, p2cwrite = os.pipe()
819 elif type(stdin) == types.IntType:
820 p2cread = stdin
821 else:
822 # Assuming file-like object
823 p2cread = stdin.fileno()
824
825 if stdout == None:
826 pass
827 elif stdout == PIPE:
828 c2pread, c2pwrite = os.pipe()
829 elif type(stdout) == types.IntType:
830 c2pwrite = stdout
831 else:
832 # Assuming file-like object
833 c2pwrite = stdout.fileno()
834
835 if stderr == None:
836 pass
837 elif stderr == PIPE:
838 errread, errwrite = os.pipe()
839 elif stderr == STDOUT:
840 errwrite = c2pwrite
841 elif type(stderr) == types.IntType:
842 errwrite = stderr
843 else:
844 # Assuming file-like object
845 errwrite = stderr.fileno()
846
847 return (p2cread, p2cwrite,
848 c2pread, c2pwrite,
849 errread, errwrite)
850
851
852 def _set_cloexec_flag(self, fd):
853 try:
854 cloexec_flag = fcntl.FD_CLOEXEC
855 except AttributeError:
856 cloexec_flag = 1
857
858 old = fcntl.fcntl(fd, fcntl.F_GETFD)
859 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
860
861
862 def _close_fds(self, but):
863 for i in range(3, MAXFD):
864 if i == but:
865 continue
866 try:
867 os.close(i)
868 except:
869 pass
870
871
872 def _execute_child(self, args, executable, preexec_fn, close_fds,
873 cwd, env, universal_newlines,
874 startupinfo, creationflags, shell,
875 p2cread, p2cwrite,
876 c2pread, c2pwrite,
877 errread, errwrite):
878 """Execute program (POSIX version)"""
879
880 if isinstance(args, types.StringTypes):
881 args = [args]
882
883 if shell:
884 args = ["/bin/sh", "-c"] + args
885
886 if executable == None:
887 executable = args[0]
888
889 # For transferring possible exec failure from child to parent
890 # The first char specifies the exception type: 0 means
891 # OSError, 1 means some other error.
892 errpipe_read, errpipe_write = os.pipe()
893 self._set_cloexec_flag(errpipe_write)
894
895 self.pid = os.fork()
896 if self.pid == 0:
897 # Child
898 try:
899 # Close parent's pipe ends
900 if p2cwrite:
901 os.close(p2cwrite)
902 if c2pread:
903 os.close(c2pread)
904 if errread:
905 os.close(errread)
906 os.close(errpipe_read)
907
908 # Dup fds for child
909 if p2cread:
910 os.dup2(p2cread, 0)
911 if c2pwrite:
912 os.dup2(c2pwrite, 1)
913 if errwrite:
914 os.dup2(errwrite, 2)
915
916 # Close pipe fds. Make sure we doesn't close the same
917 # fd more than once.
918 if p2cread:
919 os.close(p2cread)
920 if c2pwrite and c2pwrite not in (p2cread,):
921 os.close(c2pwrite)
922 if errwrite and errwrite not in (p2cread, c2pwrite):
923 os.close(errwrite)
924
925 # Close all other fds, if asked for
926 if close_fds:
927 self._close_fds(but=errpipe_write)
928
929 if cwd != None:
930 os.chdir(cwd)
931
932 if preexec_fn:
933 apply(preexec_fn)
934
935 if env == None:
936 os.execvp(executable, args)
937 else:
938 os.execvpe(executable, args, env)
939
940 except:
941 exc_type, exc_value, tb = sys.exc_info()
942 # Save the traceback and attach it to the exception object
943 exc_lines = traceback.format_exception(exc_type, exc_value, tb)
944 exc_value.child_traceback = ''.join(exc_lines)
945 os.write(errpipe_write, pickle.dumps(exc_value))
946
947 # This exitcode won't be reported to applications, so it
948 # really doesn't matter what we return.
949 os._exit(255)
950
951 # Parent
952 os.close(errpipe_write)
953 if p2cread and p2cwrite:
954 os.close(p2cread)
955 if c2pwrite and c2pread:
956 os.close(c2pwrite)
957 if errwrite and errread:
958 os.close(errwrite)
959
960 # Wait for exec to fail or succeed; possibly raising exception
961 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
962 os.close(errpipe_read)
963 if data != "":
964 child_exception = pickle.loads(data)
965 raise child_exception
966
967
968 def _handle_exitstatus(self, sts):
969 if os.WIFSIGNALED(sts):
970 self.returncode = -os.WTERMSIG(sts)
971 elif os.WIFEXITED(sts):
972 self.returncode = os.WEXITSTATUS(sts)
973 else:
974 # Should never happen
975 raise RuntimeError("Unknown child exit status!")
976
977 _active.remove(self)
978
979
980 def poll(self):
981 """Check if child process has terminated. Returns returncode
982 attribute."""
983 if self.returncode == None:
984 try:
985 pid, sts = os.waitpid(self.pid, os.WNOHANG)
986 if pid == self.pid:
987 self._handle_exitstatus(sts)
988 except os.error:
989 pass
990 return self.returncode
991
992
993 def wait(self):
994 """Wait for child process to terminate. Returns returncode
995 attribute."""
996 if self.returncode == None:
997 pid, sts = os.waitpid(self.pid, 0)
998 self._handle_exitstatus(sts)
999 return self.returncode
1000
1001
1002 def communicate(self, input=None):
1003 """Interact with process: Send data to stdin. Read data from
1004 stdout and stderr, until end-of-file is reached. Wait for
1005 process to terminate. The optional input argument should be a
1006 string to be sent to the child process, or None, if no data
1007 should be sent to the child.
1008
1009 communicate() returns a tuple (stdout, stderr)."""
1010 read_set = []
1011 write_set = []
1012 stdout = None # Return
1013 stderr = None # Return
1014
1015 if self.stdin:
1016 # Flush stdio buffer. This might block, if the user has
1017 # been writing to .stdin in an uncontrolled fashion.
1018 self.stdin.flush()
1019 if input:
1020 write_set.append(self.stdin)
1021 else:
1022 self.stdin.close()
1023 if self.stdout:
1024 read_set.append(self.stdout)
1025 stdout = []
1026 if self.stderr:
1027 read_set.append(self.stderr)
1028 stderr = []
1029
1030 while read_set or write_set:
1031 rlist, wlist, xlist = select.select(read_set, write_set, [])
1032
1033 if self.stdin in wlist:
1034 # When select has indicated that the file is writable,
1035 # we can write up to PIPE_BUF bytes without risk
1036 # blocking. POSIX defines PIPE_BUF >= 512
1037 bytes_written = os.write(self.stdin.fileno(), input[:512])
1038 input = input[bytes_written:]
1039 if not input:
1040 self.stdin.close()
1041 write_set.remove(self.stdin)
1042
1043 if self.stdout in rlist:
1044 data = os.read(self.stdout.fileno(), 1024)
1045 if data == "":
1046 self.stdout.close()
1047 read_set.remove(self.stdout)
1048 stdout.append(data)
1049
1050 if self.stderr in rlist:
1051 data = os.read(self.stderr.fileno(), 1024)
1052 if data == "":
1053 self.stderr.close()
1054 read_set.remove(self.stderr)
1055 stderr.append(data)
1056
1057 # All data exchanged. Translate lists into strings.
1058 if stdout != None:
1059 stdout = ''.join(stdout)
1060 if stderr != None:
1061 stderr = ''.join(stderr)
1062
1063 # Translate newlines, if requested. We cannot let the file
1064 # object do the translation: It is based on stdio, which is
1065 # impossible to combine with select (unless forcing no
1066 # buffering).
1067 if self.universal_newlines and hasattr(open, 'newlines'):
1068 if stdout:
1069 stdout = self._translate_newlines(stdout)
1070 if stderr:
1071 stderr = self._translate_newlines(stderr)
1072
1073 self.wait()
1074 return (stdout, stderr)
1075
1076
1077def _demo_posix():
1078 #
1079 # Example 1: Simple redirection: Get process list
1080 #
1081 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1082 print "Process list:"
1083 print plist
1084
1085 #
1086 # Example 2: Change uid before executing child
1087 #
1088 if os.getuid() == 0:
1089 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1090 p.wait()
1091
1092 #
1093 # Example 3: Connecting several subprocesses
1094 #
1095 print "Looking for 'hda'..."
1096 p1 = Popen(["dmesg"], stdout=PIPE)
1097 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1098 print repr(p2.communicate()[0])
1099
1100 #
1101 # Example 4: Catch execution error
1102 #
1103 print
1104 print "Trying a weird file..."
1105 try:
1106 print Popen(["/this/path/does/not/exist"]).communicate()
1107 except OSError, e:
1108 if e.errno == errno.ENOENT:
1109 print "The file didn't exist. I thought so..."
1110 print "Child traceback:"
1111 print e.child_traceback
1112 else:
1113 print "Error", e.errno
1114 else:
1115 print >>sys.stderr, "Gosh. No error."
1116
1117
1118def _demo_windows():
1119 #
1120 # Example 1: Connecting several subprocesses
1121 #
1122 print "Looking for 'PROMPT' in set output..."
1123 p1 = Popen("set", stdout=PIPE, shell=True)
1124 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1125 print repr(p2.communicate()[0])
1126
1127 #
1128 # Example 2: Simple execution of program
1129 #
1130 print "Executing calc..."
1131 p = Popen("calc")
1132 p.wait()
1133
1134
1135if __name__ == "__main__":
1136 if mswindows:
1137 _demo_windows()
1138 else:
1139 _demo_posix()
1140
1141