blob: 5a572d31e7346b7d5256a6afd3f542019aeed85b [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001# subprocess - Subprocesses with accessible I/O streams
2#
3# For more information about this module, see PEP 324.
4#
5# This module should remain compatible with Python 2.2, see PEP 291.
6#
7# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
8#
9# Licensed to PSF under a Contributor Agreement.
10# See http://www.python.org/2.4/license for licensing details.
11
12r"""subprocess - Subprocesses with accessible I/O streams
13
14This module allows you to spawn processes, connect to their
15input/output/error pipes, and obtain their return codes. This module
16intends to replace several other, older modules and functions, like:
17
18os.system
19os.spawn*
20os.popen*
21popen2.*
22commands.*
23
24Information about how the subprocess module can be used to replace these
25modules and functions can be found below.
26
27
28
29Using the subprocess module
30===========================
31This module defines one class called Popen:
32
33class Popen(args, bufsize=0, executable=None,
34 stdin=None, stdout=None, stderr=None,
35 preexec_fn=None, close_fds=False, shell=False,
36 cwd=None, env=None, universal_newlines=False,
37 startupinfo=None, creationflags=0):
38
39
40Arguments are:
41
42args should be a string, or a sequence of program arguments. The
43program to execute is normally the first item in the args sequence or
44string, but can be explicitly set by using the executable argument.
45
46On UNIX, with shell=False (default): In this case, the Popen class
47uses os.execvp() to execute the child program. args should normally
48be a sequence. A string will be treated as a sequence with the string
49as the only item (the program to execute).
50
51On UNIX, with shell=True: If args is a string, it specifies the
52command string to execute through the shell. If args is a sequence,
53the first item specifies the command string, and any additional items
54will be treated as additional shell arguments.
55
56On Windows: the Popen class uses CreateProcess() to execute the child
57program, which operates on strings. If args is a sequence, it will be
58converted to a string using the list2cmdline method. Please note that
59not all MS Windows applications interpret the command line the same
60way: The list2cmdline is designed for applications using the same
61rules as the MS C runtime.
62
63bufsize, if given, has the same meaning as the corresponding argument
64to the built-in open() function: 0 means unbuffered, 1 means line
65buffered, any other positive value means use a buffer of
66(approximately) that size. A negative bufsize means to use the system
67default, which usually means fully buffered. The default value for
68bufsize is 0 (unbuffered).
69
70stdin, stdout and stderr specify the executed programs' standard
71input, standard output and standard error file handles, respectively.
72Valid values are PIPE, an existing file descriptor (a positive
73integer), an existing file object, and None. PIPE indicates that a
74new pipe to the child should be created. With None, no redirection
75will occur; the child's file handles will be inherited from the
76parent. Additionally, stderr can be STDOUT, which indicates that the
77stderr data from the applications should be captured into the same
78file handle as for stdout.
79
80If preexec_fn is set to a callable object, this object will be called
81in the child process just before the child is executed.
82
83If close_fds is true, all file descriptors except 0, 1 and 2 will be
84closed before the child process is executed.
85
86if shell is true, the specified command will be executed through the
87shell.
88
89If cwd is not None, the current directory will be changed to cwd
90before the child is executed.
91
92If env is not None, it defines the environment variables for the new
93process.
94
95If universal_newlines is true, the file objects stdout and stderr are
96opened as a text files, but lines may be terminated by any of '\n',
97the Unix end-of-line convention, '\r', the Macintosh convention or
98'\r\n', the Windows convention. All of these external representations
99are seen as '\n' by the Python program. Note: This feature is only
100available if Python is built with universal newline support (the
101default). Also, the newlines attribute of the file objects stdout,
102stdin and stderr are not updated by the communicate() method.
103
104The startupinfo and creationflags, if given, will be passed to the
105underlying CreateProcess() function. They can specify things such as
106appearance of the main window and priority for the new process.
107(Windows only)
108
109
110This module also defines two shortcut functions:
111
112call(*popenargs, **kwargs):
113 Run command with arguments. Wait for command to complete, then
114 return the returncode attribute.
115
116 The arguments are the same as for the Popen constructor. Example:
117
118 retcode = call(["ls", "-l"])
119
120check_call(*popenargs, **kwargs):
121 Run command with arguments. Wait for command to complete. If the
122 exit code was zero then return, otherwise raise
123 CalledProcessError. The CalledProcessError object will have the
124 return code in the returncode attribute.
125
126 The arguments are the same as for the Popen constructor. Example:
127
128 check_call(["ls", "-l"])
129
130Exceptions
131----------
132Exceptions raised in the child process, before the new program has
133started to execute, will be re-raised in the parent. Additionally,
134the exception object will have one extra attribute called
135'child_traceback', which is a string containing traceback information
136from the childs point of view.
137
138The most common exception raised is OSError. This occurs, for
139example, when trying to execute a non-existent file. Applications
140should prepare for OSErrors.
141
142A ValueError will be raised if Popen is called with invalid arguments.
143
144check_call() will raise CalledProcessError, if the called process
145returns a non-zero return code.
146
147
148Security
149--------
150Unlike some other popen functions, this implementation will never call
151/bin/sh implicitly. This means that all characters, including shell
152metacharacters, can safely be passed to child processes.
153
154
155Popen objects
156=============
157Instances of the Popen class have the following methods:
158
159poll()
160 Check if child process has terminated. Returns returncode
161 attribute.
162
163wait()
164 Wait for child process to terminate. Returns returncode attribute.
165
166communicate(input=None)
167 Interact with process: Send data to stdin. Read data from stdout
168 and stderr, until end-of-file is reached. Wait for process to
169 terminate. The optional input argument should be a string to be
170 sent to the child process, or None, if no data should be sent to
171 the child.
172
173 communicate() returns a tuple (stdout, stderr).
174
175 Note: The data read is buffered in memory, so do not use this
176 method if the data size is large or unlimited.
177
178The following attributes are also available:
179
180stdin
181 If the stdin argument is PIPE, this attribute is a file object
182 that provides input to the child process. Otherwise, it is None.
183
184stdout
185 If the stdout argument is PIPE, this attribute is a file object
186 that provides output from the child process. Otherwise, it is
187 None.
188
189stderr
190 If the stderr argument is PIPE, this attribute is file object that
191 provides error output from the child process. Otherwise, it is
192 None.
193
194pid
195 The process ID of the child process.
196
197returncode
198 The child return code. A None value indicates that the process
199 hasn't terminated yet. A negative value -N indicates that the
200 child was terminated by signal N (UNIX only).
201
202
203Replacing older functions with the subprocess module
204====================================================
205In this section, "a ==> b" means that b can be used as a replacement
206for a.
207
208Note: All functions in this section fail (more or less) silently if
209the executed program cannot be found; this module raises an OSError
210exception.
211
212In the following examples, we assume that the subprocess module is
213imported with "from subprocess import *".
214
215
216Replacing /bin/sh shell backquote
217---------------------------------
218output=`mycmd myarg`
219==>
220output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
221
222
223Replacing shell pipe line
224-------------------------
225output=`dmesg | grep hda`
226==>
227p1 = Popen(["dmesg"], stdout=PIPE)
228p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
229output = p2.communicate()[0]
230
231
232Replacing os.system()
233---------------------
234sts = os.system("mycmd" + " myarg")
235==>
236p = Popen("mycmd" + " myarg", shell=True)
237pid, sts = os.waitpid(p.pid, 0)
238
239Note:
240
241* Calling the program through the shell is usually not required.
242
243* It's easier to look at the returncode attribute than the
244 exitstatus.
245
246A more real-world example would look like this:
247
248try:
249 retcode = call("mycmd" + " myarg", shell=True)
250 if retcode < 0:
251 print >>sys.stderr, "Child was terminated by signal", -retcode
252 else:
253 print >>sys.stderr, "Child returned", retcode
254except OSError, e:
255 print >>sys.stderr, "Execution failed:", e
256
257
258Replacing os.spawn*
259-------------------
260P_NOWAIT example:
261
262pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
263==>
264pid = Popen(["/bin/mycmd", "myarg"]).pid
265
266
267P_WAIT example:
268
269retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
270==>
271retcode = call(["/bin/mycmd", "myarg"])
272
273
274Vector example:
275
276os.spawnvp(os.P_NOWAIT, path, args)
277==>
278Popen([path] + args[1:])
279
280
281Environment example:
282
283os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
284==>
285Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
286
287
288Replacing os.popen*
289-------------------
290pipe = os.popen(cmd, mode='r', bufsize)
291==>
292pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
293
294pipe = os.popen(cmd, mode='w', bufsize)
295==>
296pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
297
298
299(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
300==>
301p = Popen(cmd, shell=True, bufsize=bufsize,
302 stdin=PIPE, stdout=PIPE, close_fds=True)
303(child_stdin, child_stdout) = (p.stdin, p.stdout)
304
305
306(child_stdin,
307 child_stdout,
308 child_stderr) = os.popen3(cmd, mode, bufsize)
309==>
310p = Popen(cmd, shell=True, bufsize=bufsize,
311 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
312(child_stdin,
313 child_stdout,
314 child_stderr) = (p.stdin, p.stdout, p.stderr)
315
316
317(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
318==>
319p = Popen(cmd, shell=True, bufsize=bufsize,
320 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
321(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
322
323
324Replacing popen2.*
325------------------
326Note: If the cmd argument to popen2 functions is a string, the command
327is executed through /bin/sh. If it is a list, the command is directly
328executed.
329
330(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
331==>
332p = Popen(["somestring"], shell=True, bufsize=bufsize
333 stdin=PIPE, stdout=PIPE, close_fds=True)
334(child_stdout, child_stdin) = (p.stdout, p.stdin)
335
336
337(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
338==>
339p = Popen(["mycmd", "myarg"], bufsize=bufsize,
340 stdin=PIPE, stdout=PIPE, close_fds=True)
341(child_stdout, child_stdin) = (p.stdout, p.stdin)
342
343The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
344except that:
345
346* subprocess.Popen raises an exception if the execution fails
347* the capturestderr argument is replaced with the stderr argument.
348* stdin=PIPE and stdout=PIPE must be specified.
349* popen2 closes all filedescriptors by default, but you have to specify
350 close_fds=True with subprocess.Popen.
351"""
352
353import sys
354mswindows = (sys.platform == "win32")
355jython = sys.platform.startswith("java")
356
357import os
358import types
359import traceback
360
361# Exception classes used by this module.
362class CalledProcessError(Exception):
363 """This exception is raised when a process run by check_call() returns
364 a non-zero exit status. The exit status will be stored in the
365 returncode attribute."""
366 def __init__(self, returncode, cmd):
367 self.returncode = returncode
368 self.cmd = cmd
369 def __str__(self):
370 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
371
372
373if mswindows:
374 import threading
375 import msvcrt
376 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
377 import pywintypes
378 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
379 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
380 from win32api import GetCurrentProcess, DuplicateHandle, \
381 GetModuleFileName, GetVersion
382 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
383 from win32pipe import CreatePipe
384 from win32process import CreateProcess, STARTUPINFO, \
385 GetExitCodeProcess, STARTF_USESTDHANDLES, \
386 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
387 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
388 else:
389 from _subprocess import *
390 class STARTUPINFO:
391 dwFlags = 0
392 hStdInput = None
393 hStdOutput = None
394 hStdError = None
395 wShowWindow = 0
396 class pywintypes:
397 error = IOError
398elif jython:
399 import errno
400 import threading
401 import java.io.File
402 import java.io.IOException
403 import java.lang.IllegalArgumentException
404 import java.lang.IllegalThreadStateException
405 import java.lang.ProcessBuilder
406 import java.lang.System
407 import java.lang.Thread
408 import java.nio.ByteBuffer
409 import org.python.core.io.RawIOBase
410 import org.python.core.io.StreamIO
411else:
412 import select
413 import errno
414 import fcntl
415 import gc
416 import pickle
417
418__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
419
420try:
421 MAXFD = os.sysconf("SC_OPEN_MAX")
422except:
423 MAXFD = 256
424
425# True/False does not exist on 2.2.0
426try:
427 False
428except NameError:
429 False = 0
430 True = 1
431
432_active = []
433
434def _cleanup():
435 for inst in _active[:]:
436 if inst.poll(_deadstate=sys.maxint) >= 0:
437 try:
438 _active.remove(inst)
439 except ValueError:
440 # This can happen if two threads create a new Popen instance.
441 # It's harmless that it was already removed, so ignore.
442 pass
443
444PIPE = -1
445STDOUT = -2
446
447
448def call(*popenargs, **kwargs):
449 """Run command with arguments. Wait for command to complete, then
450 return the returncode attribute.
451
452 The arguments are the same as for the Popen constructor. Example:
453
454 retcode = call(["ls", "-l"])
455 """
456 return Popen(*popenargs, **kwargs).wait()
457
458
459def check_call(*popenargs, **kwargs):
460 """Run command with arguments. Wait for command to complete. If
461 the exit code was zero then return, otherwise raise
462 CalledProcessError. The CalledProcessError object will have the
463 return code in the returncode attribute.
464
465 The arguments are the same as for the Popen constructor. Example:
466
467 check_call(["ls", "-l"])
468 """
469 retcode = call(*popenargs, **kwargs)
470 cmd = kwargs.get("args")
471 if cmd is None:
472 cmd = popenargs[0]
473 if retcode:
474 raise CalledProcessError(retcode, cmd)
475 return retcode
476
477
478def list2cmdline(seq):
479 """
480 Translate a sequence of arguments into a command line
481 string, using the same rules as the MS C runtime:
482
483 1) Arguments are delimited by white space, which is either a
484 space or a tab.
485
486 2) A string surrounded by double quotation marks is
487 interpreted as a single argument, regardless of white space
488 or pipe characters contained within. A quoted string can be
489 embedded in an argument.
490
491 3) A double quotation mark preceded by a backslash is
492 interpreted as a literal double quotation mark.
493
494 4) Backslashes are interpreted literally, unless they
495 immediately precede a double quotation mark.
496
497 5) If backslashes immediately precede a double quotation mark,
498 every pair of backslashes is interpreted as a literal
499 backslash. If the number of backslashes is odd, the last
500 backslash escapes the next double quotation mark as
501 described in rule 3.
502 """
503
504 # See
505 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
506 result = []
507 needquote = False
508 for arg in seq:
509 bs_buf = []
510
511 # Add a space to separate this argument from the others
512 if result:
513 result.append(' ')
514
515 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
516 if needquote:
517 result.append('"')
518
519 for c in arg:
520 if c == '\\':
521 # Don't know if we need to double yet.
522 bs_buf.append(c)
523 elif c == '"':
524 # Double backslashes.
525 result.append('\\' * len(bs_buf)*2)
526 bs_buf = []
527 result.append('\\"')
528 else:
529 # Normal char
530 if bs_buf:
531 result.extend(bs_buf)
532 bs_buf = []
533 result.append(c)
534
535 # Add remaining backslashes, if any.
536 if bs_buf:
537 result.extend(bs_buf)
538
539 if needquote:
540 result.extend(bs_buf)
541 result.append('"')
542
543 return ''.join(result)
544
545
546if jython:
547 # Parse command line arguments for Windows
548 _win_oses = ['nt']
549
550 _cmdline2listimpl = None
551 _escape_args = None
552 _shell_command = None
553
554 def _cmdline2list(cmdline):
555 """Build an argv list from a Microsoft shell style cmdline str
556
557 The reverse of list2cmdline that follows the same MS C runtime
558 rules.
559
560 Java's ProcessBuilder takes a List<String> cmdline that's joined
561 with a list2cmdline-like routine for Windows CreateProcess
562 (which takes a String cmdline). This process ruins String
563 cmdlines from the user with escapes or quotes. To avoid this we
564 first parse these cmdlines into an argv.
565
566 Runtime.exec(String) is too naive and useless for this case.
567 """
568 whitespace = ' \t'
569 # count of preceding '\'
570 bs_count = 0
571 in_quotes = False
572 arg = []
573 argv = []
574
575 for ch in cmdline:
576 if ch in whitespace and not in_quotes:
577 if arg:
578 # finalize arg and reset
579 argv.append(''.join(arg))
580 arg = []
581 bs_count = 0
582 elif ch == '\\':
583 arg.append(ch)
584 bs_count += 1
585 elif ch == '"':
586 if not bs_count % 2:
587 # Even number of '\' followed by a '"'. Place one
588 # '\' for every pair and treat '"' as a delimiter
589 if bs_count:
590 del arg[-(bs_count / 2):]
591 in_quotes = not in_quotes
592 else:
593 # Odd number of '\' followed by a '"'. Place one '\'
594 # for every pair and treat '"' as an escape sequence
595 # by the remaining '\'
596 del arg[-(bs_count / 2 + 1):]
597 arg.append(ch)
598 bs_count = 0
599 else:
600 # regular char
601 arg.append(ch)
602 bs_count = 0
603
604 # A single trailing '"' delimiter yields an empty arg
605 if arg or in_quotes:
606 argv.append(''.join(arg))
607
608 return argv
609
610 def _setup_platform():
611 """Setup the shell command and the command line argument escape
612 function depending on the underlying platform
613 """
614 global _cmdline2listimpl, _escape_args, _shell_command
615
616 if os._name in _win_oses:
617 _cmdline2listimpl = _cmdline2list
618 _escape_args = lambda args: [list2cmdline([arg]) for arg in args]
619 else:
620 _cmdline2listimpl = lambda args: [args]
621 _escape_args = lambda args: args
622
623 for shell_command in os._get_shell_commands():
624 executable = shell_command[0]
625 if not os.path.isabs(executable):
626 import distutils.spawn
627 executable = distutils.spawn.find_executable(executable)
628 if not executable or not os.path.exists(executable):
629 continue
630 shell_command[0] = executable
631 _shell_command = shell_command
632 return
633
634 if not _shell_command:
635 import warnings
636 warnings.warn('Unable to determine _shell_command for '
637 'underlying os: %s' % os._name, RuntimeWarning, 3)
638 _setup_platform()
639
640
641 class _CouplerThread(java.lang.Thread):
642
643 """Couples a reader and writer RawIOBase.
644
645 Streams data from the reader's read_func (a RawIOBase readinto
646 method) to the writer's write_func (a RawIOBase write method) in
647 a separate thread. Optionally calls close_func when finished
648 streaming or an exception occurs.
649
650 This thread will fail safe when interrupted by Java's
651 Thread.interrupt.
652 """
653
654 # analagous to PC_PIPE_BUF, which is typically 512 or 4096
655 bufsize = 4096
656
657 def __init__(self, name, read_func, write_func, close_func=None):
658 self.read_func = read_func
659 self.write_func = write_func
660 self.close_func = close_func
661 self.setName('%s-%s (%s)' % (self.__class__.__name__, id(self),
662 name))
663 self.setDaemon(True)
664
665 def run(self):
666 buf = java.nio.ByteBuffer.allocate(self.bufsize)
667 while True:
668 try:
669 count = self.read_func(buf)
670 if count < 1:
671 if self.close_func:
672 self.close_func()
673 break
674 buf.flip()
675 self.write_func(buf)
676 buf.flip()
677 except IOError, ioe:
678 if self.close_func:
679 try:
680 self.close_func()
681 except:
682 pass
683 # XXX: hack, should really be a
684 # ClosedByInterruptError(IOError) exception
685 if str(ioe) == \
686 'java.nio.channels.ClosedByInterruptException':
687 return
688 raise
689
690
691class Popen(object):
692 def __init__(self, args, bufsize=0, executable=None,
693 stdin=None, stdout=None, stderr=None,
694 preexec_fn=None, close_fds=False, shell=False,
695 cwd=None, env=None, universal_newlines=False,
696 startupinfo=None, creationflags=0):
697 """Create new Popen instance."""
698 _cleanup()
699
700 self._child_created = False
701 if not isinstance(bufsize, (int, long)):
702 raise TypeError("bufsize must be an integer")
703
704 if mswindows:
705 if preexec_fn is not None:
706 raise ValueError("preexec_fn is not supported on Windows "
707 "platforms")
708 if close_fds and (stdin is not None or stdout is not None or
709 stderr is not None):
710 raise ValueError("close_fds is not supported on Windows "
711 "platforms if you redirect stdin/stdout/stderr")
712 else:
713 # POSIX
714 if startupinfo is not None:
715 raise ValueError("startupinfo is only supported on Windows "
716 "platforms")
717 if creationflags != 0:
718 raise ValueError("creationflags is only supported on Windows "
719 "platforms")
720 if jython:
721 if preexec_fn is not None:
722 raise ValueError("preexec_fn is not supported on the Jython "
723 "platform")
724
725 self.stdin = None
726 self.stdout = None
727 self.stderr = None
728 self.pid = None
729 self.returncode = None
730 self.universal_newlines = universal_newlines
731
732 # Input and output objects. The general principle is like
733 # this:
734 #
735 # Parent Child
736 # ------ -----
737 # p2cwrite ---stdin---> p2cread
738 # c2pread <--stdout--- c2pwrite
739 # errread <--stderr--- errwrite
740 #
741 # On POSIX, the child objects are file descriptors. On
742 # Windows, these are Windows file handles. The parent objects
743 # are file descriptors on both platforms. The parent objects
744 # are None when not using PIPEs. The child objects are None
745 # when not redirecting.
746
747 (p2cread, p2cwrite,
748 c2pread, c2pwrite,
749 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
750
751 self._execute_child(args, executable, preexec_fn, close_fds,
752 cwd, env, universal_newlines,
753 startupinfo, creationflags, shell,
754 p2cread, p2cwrite,
755 c2pread, c2pwrite,
756 errread, errwrite)
757
758 # On Windows, you cannot just redirect one or two handles: You
759 # either have to redirect all three or none. If the subprocess
760 # user has only redirected one or two handles, we are
761 # automatically creating PIPEs for the rest. We should close
762 # these after the process is started. See bug #1124861.
763 if mswindows:
764 if stdin is None and p2cwrite is not None:
765 os.close(p2cwrite)
766 p2cwrite = None
767 if stdout is None and c2pread is not None:
768 os.close(c2pread)
769 c2pread = None
770 if stderr is None and errread is not None:
771 os.close(errread)
772 errread = None
773
774 if jython:
775 self._stdin_thread = None
776 self._stdout_thread = None
777 self._stderr_thread = None
778
779 # 'ct' is for _CouplerThread
780 proc = self._process
781 ct2cwrite = org.python.core.io.StreamIO(proc.getOutputStream(),
782 True)
783 c2ctread = org.python.core.io.StreamIO(proc.getInputStream(), True)
784 cterrread = org.python.core.io.StreamIO(proc.getErrorStream(),
785 True)
786
787 # Use the java.lang.Process streams for PIPE, otherwise
788 # direct the desired file to/from the java.lang.Process
789 # streams in a separate thread
790 if p2cwrite == PIPE:
791 p2cwrite = ct2cwrite
792 else:
793 if p2cread is None:
794 # Coupling stdin is not supported: there's no way to
795 # cleanly interrupt it if it blocks the
796 # _CouplerThread forever (we can Thread.interrupt()
797 # its _CouplerThread but that closes stdin's
798 # Channel)
799 pass
800 else:
801 self._stdin_thread = self._coupler_thread('stdin',
802 p2cread.readinto,
803 ct2cwrite.write,
804 ct2cwrite.close)
805 self._stdin_thread.start()
806
807 if c2pread == PIPE:
808 c2pread = c2ctread
809 else:
810 if c2pwrite is None:
811 c2pwrite = org.python.core.io.StreamIO(
812 java.lang.System.out, False)
813 self._stdout_thread = self._coupler_thread('stdout',
814 c2ctread.readinto,
815 c2pwrite.write)
816 self._stdout_thread.start()
817
818 if errread == PIPE:
819 errread = cterrread
820 elif not self._stderr_is_stdout(errwrite, c2pwrite):
821 if errwrite is None:
822 errwrite = org.python.core.io.StreamIO(
823 java.lang.System.err, False)
824 self._stderr_thread = self._coupler_thread('stderr',
825 cterrread.readinto,
826 errwrite.write)
827 self._stderr_thread.start()
828
829 if p2cwrite is not None:
830 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
831 if c2pread is not None:
832 if universal_newlines:
833 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
834 else:
835 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
836 if errread is not None:
837 if universal_newlines:
838 self.stderr = os.fdopen(errread, 'rU', bufsize)
839 else:
840 self.stderr = os.fdopen(errread, 'rb', bufsize)
841
842
843 def _translate_newlines(self, data):
844 data = data.replace("\r\n", "\n")
845 data = data.replace("\r", "\n")
846 return data
847
848
849 def __del__(self, sys=sys):
850 if not self._child_created:
851 # We didn't get to successfully create a child process.
852 return
853 # In case the child hasn't been waited on, check if it's done.
854 self.poll(_deadstate=sys.maxint)
855 if self.returncode is None and _active is not None:
856 # Child is still running, keep us alive until we can wait on it.
857 _active.append(self)
858
859
860 def communicate(self, input=None):
861 """Interact with process: Send data to stdin. Read data from
862 stdout and stderr, until end-of-file is reached. Wait for
863 process to terminate. The optional input argument should be a
864 string to be sent to the child process, or None, if no data
865 should be sent to the child.
866
867 communicate() returns a tuple (stdout, stderr)."""
868
869 # Optimization: If we are only using one pipe, or no pipe at
870 # all, using select() or threads is unnecessary.
871 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
872 stdout = None
873 stderr = None
874 if self.stdin:
875 if input:
876 self.stdin.write(input)
877 self.stdin.close()
878 elif self.stdout:
879 stdout = self.stdout.read()
880 elif self.stderr:
881 stderr = self.stderr.read()
882 self.wait()
883 return (stdout, stderr)
884
885 return self._communicate(input)
886
887
888 if mswindows or jython:
889 #
890 # Windows and Jython shared methods
891 #
892 def _readerthread(self, fh, buffer):
893 buffer.append(fh.read())
894
895
896 def _communicate(self, input):
897 stdout = None # Return
898 stderr = None # Return
899
900 if self.stdout:
901 stdout = []
902 stdout_thread = threading.Thread(target=self._readerthread,
903 args=(self.stdout, stdout))
904 stdout_thread.setDaemon(True)
905 stdout_thread.start()
906 if self.stderr:
907 stderr = []
908 stderr_thread = threading.Thread(target=self._readerthread,
909 args=(self.stderr, stderr))
910 stderr_thread.setDaemon(True)
911 stderr_thread.start()
912
913 if self.stdin:
914 if input is not None:
915 self.stdin.write(input)
916 self.stdin.close()
917
918 if self.stdout:
919 stdout_thread.join()
920 if self.stderr:
921 stderr_thread.join()
922
923 # All data exchanged. Translate lists into strings.
924 if stdout is not None:
925 stdout = stdout[0]
926 if stderr is not None:
927 stderr = stderr[0]
928
929 # Translate newlines, if requested. We cannot let the file
930 # object do the translation: It is based on stdio, which is
931 # impossible to combine with select (unless forcing no
932 # buffering).
933 if self.universal_newlines and hasattr(file, 'newlines'):
934 if stdout:
935 stdout = self._translate_newlines(stdout)
936 if stderr:
937 stderr = self._translate_newlines(stderr)
938
939 self.wait()
940 return (stdout, stderr)
941
942
943 if mswindows:
944 #
945 # Windows methods
946 #
947 def _get_handles(self, stdin, stdout, stderr):
948 """Construct and return tupel with IO objects:
949 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
950 """
951 if stdin is None and stdout is None and stderr is None:
952 return (None, None, None, None, None, None)
953
954 p2cread, p2cwrite = None, None
955 c2pread, c2pwrite = None, None
956 errread, errwrite = None, None
957
958 if stdin is None:
959 p2cread = GetStdHandle(STD_INPUT_HANDLE)
960 if p2cread is not None:
961 pass
962 elif stdin is None or stdin == PIPE:
963 p2cread, p2cwrite = CreatePipe(None, 0)
964 # Detach and turn into fd
965 p2cwrite = p2cwrite.Detach()
966 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
967 elif isinstance(stdin, int):
968 p2cread = msvcrt.get_osfhandle(stdin)
969 else:
970 # Assuming file-like object
971 p2cread = msvcrt.get_osfhandle(stdin.fileno())
972 p2cread = self._make_inheritable(p2cread)
973
974 if stdout is None:
975 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
976 if c2pwrite is not None:
977 pass
978 elif stdout is None or stdout == PIPE:
979 c2pread, c2pwrite = CreatePipe(None, 0)
980 # Detach and turn into fd
981 c2pread = c2pread.Detach()
982 c2pread = msvcrt.open_osfhandle(c2pread, 0)
983 elif isinstance(stdout, int):
984 c2pwrite = msvcrt.get_osfhandle(stdout)
985 else:
986 # Assuming file-like object
987 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
988 c2pwrite = self._make_inheritable(c2pwrite)
989
990 if stderr is None:
991 errwrite = GetStdHandle(STD_ERROR_HANDLE)
992 if errwrite is not None:
993 pass
994 elif stderr is None or stderr == PIPE:
995 errread, errwrite = CreatePipe(None, 0)
996 # Detach and turn into fd
997 errread = errread.Detach()
998 errread = msvcrt.open_osfhandle(errread, 0)
999 elif stderr == STDOUT:
1000 errwrite = c2pwrite
1001 elif isinstance(stderr, int):
1002 errwrite = msvcrt.get_osfhandle(stderr)
1003 else:
1004 # Assuming file-like object
1005 errwrite = msvcrt.get_osfhandle(stderr.fileno())
1006 errwrite = self._make_inheritable(errwrite)
1007
1008 return (p2cread, p2cwrite,
1009 c2pread, c2pwrite,
1010 errread, errwrite)
1011
1012
1013 def _make_inheritable(self, handle):
1014 """Return a duplicate of handle, which is inheritable"""
1015 return DuplicateHandle(GetCurrentProcess(), handle,
1016 GetCurrentProcess(), 0, 1,
1017 DUPLICATE_SAME_ACCESS)
1018
1019
1020 def _find_w9xpopen(self):
1021 """Find and return absolut path to w9xpopen.exe"""
1022 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
1023 "w9xpopen.exe")
1024 if not os.path.exists(w9xpopen):
1025 # Eeek - file-not-found - possibly an embedding
1026 # situation - see if we can locate it in sys.exec_prefix
1027 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
1028 "w9xpopen.exe")
1029 if not os.path.exists(w9xpopen):
1030 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
1031 "needed for Popen to work with your "
1032 "shell or platform.")
1033 return w9xpopen
1034
1035
1036 def _execute_child(self, args, executable, preexec_fn, close_fds,
1037 cwd, env, universal_newlines,
1038 startupinfo, creationflags, shell,
1039 p2cread, p2cwrite,
1040 c2pread, c2pwrite,
1041 errread, errwrite):
1042 """Execute program (MS Windows version)"""
1043
1044 if not isinstance(args, types.StringTypes):
1045 args = list2cmdline(args)
1046
1047 # Process startup details
1048 if startupinfo is None:
1049 startupinfo = STARTUPINFO()
1050 if None not in (p2cread, c2pwrite, errwrite):
1051 startupinfo.dwFlags |= STARTF_USESTDHANDLES
1052 startupinfo.hStdInput = p2cread
1053 startupinfo.hStdOutput = c2pwrite
1054 startupinfo.hStdError = errwrite
1055
1056 if shell:
1057 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
1058 startupinfo.wShowWindow = SW_HIDE
1059 comspec = os.environ.get("COMSPEC", "cmd.exe")
1060 args = comspec + " /c " + args
1061 if (GetVersion() >= 0x80000000L or
1062 os.path.basename(comspec).lower() == "command.com"):
1063 # Win9x, or using command.com on NT. We need to
1064 # use the w9xpopen intermediate program. For more
1065 # information, see KB Q150956
1066 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
1067 w9xpopen = self._find_w9xpopen()
1068 args = '"%s" %s' % (w9xpopen, args)
1069 # Not passing CREATE_NEW_CONSOLE has been known to
1070 # cause random failures on win9x. Specifically a
1071 # dialog: "Your program accessed mem currently in
1072 # use at xxx" and a hopeful warning about the
1073 # stability of your system. Cost is Ctrl+C wont
1074 # kill children.
1075 creationflags |= CREATE_NEW_CONSOLE
1076
1077 # Start the process
1078 try:
1079 hp, ht, pid, tid = CreateProcess(executable, args,
1080 # no special security
1081 None, None,
1082 int(not close_fds),
1083 creationflags,
1084 env,
1085 cwd,
1086 startupinfo)
1087 except pywintypes.error, e:
1088 # Translate pywintypes.error to WindowsError, which is
1089 # a subclass of OSError. FIXME: We should really
1090 # translate errno using _sys_errlist (or simliar), but
1091 # how can this be done from Python?
1092 raise WindowsError(*e.args)
1093
1094 # Retain the process handle, but close the thread handle
1095 self._child_created = True
1096 self._handle = hp
1097 self.pid = pid
1098 ht.Close()
1099
1100 # Child is launched. Close the parent's copy of those pipe
1101 # handles that only the child should have open. You need
1102 # to make sure that no handles to the write end of the
1103 # output pipe are maintained in this process or else the
1104 # pipe will not close when the child process exits and the
1105 # ReadFile will hang.
1106 if p2cread is not None:
1107 p2cread.Close()
1108 if c2pwrite is not None:
1109 c2pwrite.Close()
1110 if errwrite is not None:
1111 errwrite.Close()
1112
1113
1114 def poll(self, _deadstate=None):
1115 """Check if child process has terminated. Returns returncode
1116 attribute."""
1117 if self.returncode is None:
1118 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
1119 self.returncode = GetExitCodeProcess(self._handle)
1120 return self.returncode
1121
1122
1123 def wait(self):
1124 """Wait for child process to terminate. Returns returncode
1125 attribute."""
1126 if self.returncode is None:
1127 obj = WaitForSingleObject(self._handle, INFINITE)
1128 self.returncode = GetExitCodeProcess(self._handle)
1129 return self.returncode
1130
1131 elif jython:
1132 #
1133 # Jython methods
1134 #
1135 def _get_handles(self, stdin, stdout, stderr):
1136 """Construct and return tuple with IO objects:
1137 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1138 """
1139 p2cread, p2cwrite = None, None
1140 c2pread, c2pwrite = None, None
1141 errread, errwrite = None, None
1142
1143 if stdin is None:
1144 pass
1145 elif stdin == PIPE:
1146 p2cwrite = PIPE
1147 elif isinstance(stdin, org.python.core.io.RawIOBase):
1148 p2cread = stdin
1149 else:
1150 # Assuming file-like object
1151 p2cread = stdin.fileno()
1152
1153 if stdout is None:
1154 pass
1155 elif stdout == PIPE:
1156 c2pread = PIPE
1157 elif isinstance(stdout, org.python.core.io.RawIOBase):
1158 c2pwrite = stdout
1159 else:
1160 # Assuming file-like object
1161 c2pwrite = stdout.fileno()
1162
1163 if stderr is None:
1164 pass
1165 elif stderr == PIPE:
1166 errread = PIPE
1167 elif (stderr == STDOUT or
1168 isinstance(stderr, org.python.core.io.RawIOBase)):
1169 errwrite = stderr
1170 else:
1171 # Assuming file-like object
1172 errwrite = stderr.fileno()
1173
1174 return (p2cread, p2cwrite,
1175 c2pread, c2pwrite,
1176 errread, errwrite)
1177
1178
1179 def _stderr_is_stdout(self, errwrite, c2pwrite):
1180 """Determine if the subprocess' stderr should be redirected
1181 to stdout
1182 """
1183 return (errwrite == STDOUT or c2pwrite not in (None, PIPE) and
1184 c2pwrite is errwrite)
1185
1186
1187 def _coupler_thread(self, *args, **kwargs):
1188 """Return a _CouplerThread"""
1189 return _CouplerThread(*args, **kwargs)
1190
1191
1192 def _setup_env(self, env, builder_env):
1193 """Carefully merge env with ProcessBuilder's only
1194 overwriting key/values that differ
1195
1196 System.getenv (Map<String, String>) may be backed by
1197 <byte[], byte[]> on UNIX platforms where these are really
1198 bytes. ProcessBuilder's env inherits its contents and will
1199 maintain those byte values (which may be butchered as
1200 Strings) for the subprocess if they haven't been modified.
1201 """
1202 # Determine what's safe to merge
1203 merge_env = dict((key, value) for key, value in env.iteritems()
1204 if key not in builder_env or
1205 builder_env.get(key) != value)
1206
1207 # Prune anything not in env
1208 entries = builder_env.entrySet().iterator()
1209 for entry in entries:
1210 if entry.getKey() not in env:
1211 entries.remove()
1212
1213 builder_env.putAll(merge_env)
1214
1215
1216 def _execute_child(self, args, executable, preexec_fn, close_fds,
1217 cwd, env, universal_newlines,
1218 startupinfo, creationflags, shell,
1219 p2cread, p2cwrite,
1220 c2pread, c2pwrite,
1221 errread, errwrite):
1222 """Execute program (Java version)"""
1223
1224 if isinstance(args, types.StringTypes):
1225 args = _cmdline2listimpl(args)
1226 else:
1227 args = list(args)
1228 # NOTE: CPython posix (execv) will str() any unicode
1229 # args first, maybe we should do the same on
1230 # posix. Windows passes unicode through, however
1231 if any(not isinstance(arg, (str, unicode)) for arg in args):
1232 raise TypeError('args must contain only strings')
1233 args = _escape_args(args)
1234
1235 if shell:
1236 args = _shell_command + args
1237
1238 if executable is not None:
1239 args[0] = executable
1240
1241 builder = java.lang.ProcessBuilder(args)
1242 # os.environ may be inherited for compatibility with CPython
1243 self._setup_env(dict(os.environ if env is None else env),
1244 builder.environment())
1245
1246 if cwd is None:
1247 cwd = os.getcwd()
1248 elif not os.path.exists(cwd):
1249 raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), cwd)
1250 elif not os.path.isdir(cwd):
1251 raise OSError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), cwd)
1252 builder.directory(java.io.File(cwd))
1253
1254 # Let Java manage redirection of stderr to stdout (it's more
1255 # accurate at doing so than _CouplerThreads). We redirect
1256 # not only when stderr is marked as STDOUT, but also when
1257 # c2pwrite is errwrite
1258 if self._stderr_is_stdout(errwrite, c2pwrite):
1259 builder.redirectErrorStream(True)
1260
1261 try:
1262 self._process = builder.start()
1263 except (java.io.IOException,
1264 java.lang.IllegalArgumentException), e:
1265 raise OSError(e.getMessage() or e)
1266 self._child_created = True
1267
1268
1269 def poll(self, _deadstate=None):
1270 """Check if child process has terminated. Returns returncode
1271 attribute."""
1272 if self.returncode is None:
1273 try:
1274 self.returncode = self._process.exitValue()
1275 except java.lang.IllegalThreadStateException:
1276 pass
1277 return self.returncode
1278
1279
1280 def wait(self):
1281 """Wait for child process to terminate. Returns returncode
1282 attribute."""
1283 if self.returncode is None:
1284 self.returncode = self._process.waitFor()
1285 for coupler in (self._stdout_thread, self._stderr_thread):
1286 if coupler:
1287 coupler.join()
1288 if self._stdin_thread:
1289 # The stdin thread may be blocked forever, forcibly
1290 # stop it
1291 self._stdin_thread.interrupt()
1292 return self.returncode
1293
1294 else:
1295 #
1296 # POSIX methods
1297 #
1298 def _get_handles(self, stdin, stdout, stderr):
1299 """Construct and return tupel with IO objects:
1300 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1301 """
1302 p2cread, p2cwrite = None, None
1303 c2pread, c2pwrite = None, None
1304 errread, errwrite = None, None
1305
1306 if stdin is None:
1307 pass
1308 elif stdin == PIPE:
1309 p2cread, p2cwrite = os.pipe()
1310 elif isinstance(stdin, int):
1311 p2cread = stdin
1312 else:
1313 # Assuming file-like object
1314 p2cread = stdin.fileno()
1315
1316 if stdout is None:
1317 pass
1318 elif stdout == PIPE:
1319 c2pread, c2pwrite = os.pipe()
1320 elif isinstance(stdout, int):
1321 c2pwrite = stdout
1322 else:
1323 # Assuming file-like object
1324 c2pwrite = stdout.fileno()
1325
1326 if stderr is None:
1327 pass
1328 elif stderr == PIPE:
1329 errread, errwrite = os.pipe()
1330 elif stderr == STDOUT:
1331 errwrite = c2pwrite
1332 elif isinstance(stderr, int):
1333 errwrite = stderr
1334 else:
1335 # Assuming file-like object
1336 errwrite = stderr.fileno()
1337
1338 return (p2cread, p2cwrite,
1339 c2pread, c2pwrite,
1340 errread, errwrite)
1341
1342
1343 def _set_cloexec_flag(self, fd):
1344 try:
1345 cloexec_flag = fcntl.FD_CLOEXEC
1346 except AttributeError:
1347 cloexec_flag = 1
1348
1349 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1350 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1351
1352
1353 def _close_fds(self, but):
1354 os.closerange(3, but)
1355 os.closerange(but + 1, MAXFD)
1356
1357
1358 def _execute_child(self, args, executable, preexec_fn, close_fds,
1359 cwd, env, universal_newlines,
1360 startupinfo, creationflags, shell,
1361 p2cread, p2cwrite,
1362 c2pread, c2pwrite,
1363 errread, errwrite):
1364 """Execute program (POSIX version)"""
1365
1366 if isinstance(args, types.StringTypes):
1367 args = [args]
1368 else:
1369 args = list(args)
1370
1371 if shell:
1372 args = ["/bin/sh", "-c"] + args
1373
1374 if executable is None:
1375 executable = args[0]
1376
1377 # For transferring possible exec failure from child to parent
1378 # The first char specifies the exception type: 0 means
1379 # OSError, 1 means some other error.
1380 errpipe_read, errpipe_write = os.pipe()
1381 self._set_cloexec_flag(errpipe_write)
1382
1383 gc_was_enabled = gc.isenabled()
1384 # Disable gc to avoid bug where gc -> file_dealloc ->
1385 # write to stderr -> hang. http://bugs.python.org/issue1336
1386 gc.disable()
1387 try:
1388 self.pid = os.fork()
1389 except:
1390 if gc_was_enabled:
1391 gc.enable()
1392 raise
1393 self._child_created = True
1394 if self.pid == 0:
1395 # Child
1396 try:
1397 # Close parent's pipe ends
1398 if p2cwrite is not None:
1399 os.close(p2cwrite)
1400 if c2pread is not None:
1401 os.close(c2pread)
1402 if errread is not None:
1403 os.close(errread)
1404 os.close(errpipe_read)
1405
1406 # Dup fds for child
1407 if p2cread is not None:
1408 os.dup2(p2cread, 0)
1409 if c2pwrite is not None:
1410 os.dup2(c2pwrite, 1)
1411 if errwrite is not None:
1412 os.dup2(errwrite, 2)
1413
1414 # Close pipe fds. Make sure we don't close the same
1415 # fd more than once, or standard fds.
1416 if p2cread is not None and p2cread not in (0,):
1417 os.close(p2cread)
1418 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
1419 os.close(c2pwrite)
1420 if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
1421 os.close(errwrite)
1422
1423 # Close all other fds, if asked for
1424 if close_fds:
1425 self._close_fds(but=errpipe_write)
1426
1427 if cwd is not None:
1428 os.chdir(cwd)
1429
1430 if preexec_fn:
1431 apply(preexec_fn)
1432
1433 if env is None:
1434 os.execvp(executable, args)
1435 else:
1436 os.execvpe(executable, args, env)
1437
1438 except:
1439 exc_type, exc_value, tb = sys.exc_info()
1440 # Save the traceback and attach it to the exception object
1441 exc_lines = traceback.format_exception(exc_type,
1442 exc_value,
1443 tb)
1444 exc_value.child_traceback = ''.join(exc_lines)
1445 os.write(errpipe_write, pickle.dumps(exc_value))
1446
1447 # This exitcode won't be reported to applications, so it
1448 # really doesn't matter what we return.
1449 os._exit(255)
1450
1451 # Parent
1452 if gc_was_enabled:
1453 gc.enable()
1454 os.close(errpipe_write)
1455 if p2cread is not None and p2cwrite is not None:
1456 os.close(p2cread)
1457 if c2pwrite is not None and c2pread is not None:
1458 os.close(c2pwrite)
1459 if errwrite is not None and errread is not None:
1460 os.close(errwrite)
1461
1462 # Wait for exec to fail or succeed; possibly raising exception
1463 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1464 os.close(errpipe_read)
1465 if data != "":
1466 os.waitpid(self.pid, 0)
1467 child_exception = pickle.loads(data)
1468 raise child_exception
1469
1470
1471 def _handle_exitstatus(self, sts):
1472 if os.WIFSIGNALED(sts):
1473 self.returncode = -os.WTERMSIG(sts)
1474 elif os.WIFEXITED(sts):
1475 self.returncode = os.WEXITSTATUS(sts)
1476 else:
1477 # Should never happen
1478 raise RuntimeError("Unknown child exit status!")
1479
1480
1481 def poll(self, _deadstate=None):
1482 """Check if child process has terminated. Returns returncode
1483 attribute."""
1484 if self.returncode is None:
1485 try:
1486 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1487 if pid == self.pid:
1488 self._handle_exitstatus(sts)
1489 except os.error:
1490 if _deadstate is not None:
1491 self.returncode = _deadstate
1492 return self.returncode
1493
1494
1495 def wait(self):
1496 """Wait for child process to terminate. Returns returncode
1497 attribute."""
1498 if self.returncode is None:
1499 pid, sts = os.waitpid(self.pid, 0)
1500 self._handle_exitstatus(sts)
1501 return self.returncode
1502
1503
1504 def _communicate(self, input):
1505 read_set = []
1506 write_set = []
1507 stdout = None # Return
1508 stderr = None # Return
1509
1510 if self.stdin:
1511 # Flush stdio buffer. This might block, if the user has
1512 # been writing to .stdin in an uncontrolled fashion.
1513 self.stdin.flush()
1514 if input:
1515 write_set.append(self.stdin)
1516 else:
1517 self.stdin.close()
1518 if self.stdout:
1519 read_set.append(self.stdout)
1520 stdout = []
1521 if self.stderr:
1522 read_set.append(self.stderr)
1523 stderr = []
1524
1525 input_offset = 0
1526 while read_set or write_set:
1527 rlist, wlist, xlist = select.select(read_set, write_set, [])
1528
1529 if self.stdin in wlist:
1530 # When select has indicated that the file is writable,
1531 # we can write up to PIPE_BUF bytes without risk
1532 # blocking. POSIX defines PIPE_BUF >= 512
1533 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512))
1534 input_offset += bytes_written
1535 if input_offset >= len(input):
1536 self.stdin.close()
1537 write_set.remove(self.stdin)
1538
1539 if self.stdout in rlist:
1540 data = os.read(self.stdout.fileno(), 1024)
1541 if data == "":
1542 self.stdout.close()
1543 read_set.remove(self.stdout)
1544 stdout.append(data)
1545
1546 if self.stderr in rlist:
1547 data = os.read(self.stderr.fileno(), 1024)
1548 if data == "":
1549 self.stderr.close()
1550 read_set.remove(self.stderr)
1551 stderr.append(data)
1552
1553 # All data exchanged. Translate lists into strings.
1554 if stdout is not None:
1555 stdout = ''.join(stdout)
1556 if stderr is not None:
1557 stderr = ''.join(stderr)
1558
1559 # Translate newlines, if requested. We cannot let the file
1560 # object do the translation: It is based on stdio, which is
1561 # impossible to combine with select (unless forcing no
1562 # buffering).
1563 if self.universal_newlines and hasattr(file, 'newlines'):
1564 if stdout:
1565 stdout = self._translate_newlines(stdout)
1566 if stderr:
1567 stderr = self._translate_newlines(stderr)
1568
1569 self.wait()
1570 return (stdout, stderr)
1571
1572
1573def _demo_posix():
1574 #
1575 # Example 1: Simple redirection: Get process list
1576 #
1577 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1578 print "Process list:"
1579 print plist
1580
1581 #
1582 # Example 2: Change uid before executing child
1583 #
1584 if os.getuid() == 0:
1585 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1586 p.wait()
1587
1588 #
1589 # Example 3: Connecting several subprocesses
1590 #
1591 print "Looking for 'hda'..."
1592 p1 = Popen(["dmesg"], stdout=PIPE)
1593 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1594 print repr(p2.communicate()[0])
1595
1596 #
1597 # Example 4: Catch execution error
1598 #
1599 print
1600 print "Trying a weird file..."
1601 try:
1602 print Popen(["/this/path/does/not/exist"]).communicate()
1603 except OSError, e:
1604 if e.errno == errno.ENOENT:
1605 print "The file didn't exist. I thought so..."
1606 print "Child traceback:"
1607 print e.child_traceback
1608 else:
1609 print "Error", e.errno
1610 else:
1611 print >>sys.stderr, "Gosh. No error."
1612
1613
1614def _demo_windows():
1615 #
1616 # Example 1: Connecting several subprocesses
1617 #
1618 print "Looking for 'PROMPT' in set output..."
1619 p1 = Popen("set", stdout=PIPE, shell=True)
1620 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1621 print repr(p2.communicate()[0])
1622
1623 #
1624 # Example 2: Simple execution of program
1625 #
1626 print "Executing calc..."
1627 p = Popen("calc")
1628 p.wait()
1629
1630
1631def _demo_jython():
1632 #
1633 # Example 1: Return the number of processors on this machine
1634 #
1635 print "Running a jython subprocess to return the number of processors..."
1636 p = Popen([sys.executable, "-c",
1637 ('import sys;'
1638 'from java.lang import Runtime;'
1639 'sys.exit(Runtime.getRuntime().availableProcessors())')])
1640 print p.wait()
1641
1642 #
1643 # Example 2: Connecting several subprocesses
1644 #
1645 print "Connecting two jython subprocesses..."
1646 p1 = Popen([sys.executable, "-c",
1647 ('import os;'
1648 'print os.environ["foo"]')], env=dict(foo='bar'),
1649 stdout=PIPE)
1650 p2 = Popen([sys.executable, "-c",
1651 ('import os, sys;'
1652 'their_foo = sys.stdin.read().strip();'
1653 'my_foo = os.environ["foo"];'
1654 'msg = "Their env\'s foo: %r, My env\'s foo: %r";'
1655 'print msg % (their_foo, my_foo)')],
1656 env=dict(foo='baz'), stdin=p1.stdout, stdout=PIPE)
1657 print p2.communicate()[0]
1658
1659
1660if __name__ == "__main__":
1661 if mswindows:
1662 _demo_windows()
1663 elif jython:
1664 _demo_jython()
1665 else:
1666 _demo_posix()