home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / subprocess.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  20.6 KB  |  799 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. import sys
  5. mswindows = sys.platform == 'win32'
  6. import os
  7. import types
  8. import traceback
  9. import gc
  10. import signal
  11.  
  12. class CalledProcessError(Exception):
  13.     
  14.     def __init__(self, returncode, cmd, output = None):
  15.         self.returncode = returncode
  16.         self.cmd = cmd
  17.         self.output = output
  18.  
  19.     
  20.     def __str__(self):
  21.         return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  22.  
  23.  
  24. if mswindows:
  25.     import threading
  26.     import msvcrt
  27.     import _subprocess
  28.     
  29.     class STARTUPINFO:
  30.         dwFlags = 0
  31.         hStdInput = None
  32.         hStdOutput = None
  33.         hStdError = None
  34.         wShowWindow = 0
  35.  
  36.     
  37.     class pywintypes:
  38.         error = IOError
  39.  
  40. else:
  41.     import select
  42.     _has_poll = hasattr(select, 'poll')
  43.     import errno
  44.     import fcntl
  45.     import pickle
  46.     _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  47. __all__ = [
  48.     'Popen',
  49.     'PIPE',
  50.     'STDOUT',
  51.     'call',
  52.     'check_call',
  53.     'check_output',
  54.     'CalledProcessError']
  55. if mswindows:
  56.     from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
  57.     __all__.extend([
  58.         'CREATE_NEW_CONSOLE',
  59.         'CREATE_NEW_PROCESS_GROUP'])
  60.  
  61. try:
  62.     MAXFD = os.sysconf('SC_OPEN_MAX')
  63. except:
  64.     MAXFD = 256
  65.  
  66. _active = []
  67.  
  68. def _cleanup():
  69.     for inst in _active[:]:
  70.         res = inst._internal_poll(_deadstate = sys.maxint)
  71.         if res is not None and res >= 0:
  72.             
  73.             try:
  74.                 _active.remove(inst)
  75.             except ValueError:
  76.                 pass
  77.             
  78.  
  79.  
  80. PIPE = -1
  81. STDOUT = -2
  82.  
  83. def _eintr_retry_call(func, *args):
  84.     while True:
  85.         
  86.         try:
  87.             return func(*args)
  88.         continue
  89.         except OSError:
  90.             e = None
  91.             if e.errno == errno.EINTR:
  92.                 continue
  93.             raise 
  94.             continue
  95.         
  96.  
  97.  
  98.  
  99. def call(*popenargs, **kwargs):
  100.     return Popen(*popenargs, **kwargs).wait()
  101.  
  102.  
  103. def check_call(*popenargs, **kwargs):
  104.     retcode = call(*popenargs, **kwargs)
  105.     if retcode:
  106.         cmd = kwargs.get('args')
  107.         if cmd is None:
  108.             cmd = popenargs[0]
  109.         raise CalledProcessError(retcode, cmd)
  110.     return 0
  111.  
  112.  
  113. def check_output(*popenargs, **kwargs):
  114.     if 'stdout' in kwargs:
  115.         raise ValueError('stdout argument not allowed, it will be overridden.')
  116.     process = Popen(stdout = PIPE, *popenargs, **kwargs)
  117.     (output, unused_err) = process.communicate()
  118.     retcode = process.poll()
  119.     if retcode:
  120.         cmd = kwargs.get('args')
  121.         if cmd is None:
  122.             cmd = popenargs[0]
  123.         raise CalledProcessError(retcode, cmd, output = output)
  124.     return output
  125.  
  126.  
  127. def list2cmdline(seq):
  128.     result = []
  129.     needquote = False
  130.     for arg in seq:
  131.         bs_buf = []
  132.         if result:
  133.             result.append(' ')
  134.         if not ' ' in arg and '\t' in arg:
  135.             pass
  136.         needquote = not arg
  137.         if needquote:
  138.             result.append('"')
  139.         for c in arg:
  140.             if c == '\\':
  141.                 bs_buf.append(c)
  142.                 continue
  143.             if c == '"':
  144.                 result.append('\\' * len(bs_buf) * 2)
  145.                 bs_buf = []
  146.                 result.append('\\"')
  147.                 continue
  148.             if bs_buf:
  149.                 result.extend(bs_buf)
  150.                 bs_buf = []
  151.             result.append(c)
  152.         
  153.         if bs_buf:
  154.             result.extend(bs_buf)
  155.         if needquote:
  156.             result.extend(bs_buf)
  157.             result.append('"')
  158.             continue
  159.     return ''.join(result)
  160.  
  161.  
  162. class Popen(object):
  163.     
  164.     def __init__(self, args, bufsize = 0, executable = None, stdin = None, stdout = None, stderr = None, preexec_fn = None, close_fds = False, shell = False, cwd = None, env = None, universal_newlines = False, startupinfo = None, creationflags = 0):
  165.         _cleanup()
  166.         self._child_created = False
  167.         if not isinstance(bufsize, (int, long)):
  168.             raise TypeError('bufsize must be an integer')
  169.         if mswindows:
  170.             if preexec_fn is not None:
  171.                 raise ValueError('preexec_fn is not supported on Windows platforms')
  172.             if close_fds:
  173.                 if stdin is not None and stdout is not None or stderr is not None:
  174.                     raise ValueError('close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr')
  175.             elif startupinfo is not None:
  176.                 raise ValueError('startupinfo is only supported on Windows platforms')
  177.             if creationflags != 0:
  178.                 raise ValueError('creationflags is only supported on Windows platforms')
  179.             self.stdin = None
  180.             self.stdout = None
  181.             self.stderr = None
  182.             self.pid = None
  183.             self.returncode = None
  184.             self.universal_newlines = universal_newlines
  185.             (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  186.             self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  187.             if mswindows:
  188.                 if p2cwrite is not None:
  189.                     p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  190.                 if c2pread is not None:
  191.                     c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  192.                 if errread is not None:
  193.                     errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  194.                 
  195.             if p2cwrite is not None:
  196.                 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  197.             if c2pread is not None:
  198.                 if universal_newlines:
  199.                     self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  200.                 else:
  201.                     self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  202.             if errread is not None:
  203.                 if universal_newlines:
  204.                     self.stderr = os.fdopen(errread, 'rU', bufsize)
  205.                 else:
  206.                     self.stderr = os.fdopen(errread, 'rb', bufsize)
  207.             return None
  208.  
  209.     
  210.     def _translate_newlines(self, data):
  211.         data = data.replace('\r\n', '\n')
  212.         data = data.replace('\r', '\n')
  213.         return data
  214.  
  215.     
  216.     def __del__(self, _maxint = sys.maxint, _active = _active):
  217.         if not self._child_created:
  218.             return None
  219.         None._internal_poll(_deadstate = _maxint)
  220.         if self.returncode is None and _active is not None:
  221.             _active.append(self)
  222.  
  223.     
  224.     def communicate(self, input = None):
  225.         if [
  226.             self.stdin,
  227.             self.stdout,
  228.             self.stderr].count(None) >= 2:
  229.             stdout = None
  230.             stderr = None
  231.             if self.stdin:
  232.                 if input:
  233.                     self.stdin.write(input)
  234.                 self.stdin.close()
  235.             elif self.stdout:
  236.                 stdout = self.stdout.read()
  237.                 self.stdout.close()
  238.             elif self.stderr:
  239.                 stderr = self.stderr.read()
  240.                 self.stderr.close()
  241.             self.wait()
  242.             return (stdout, stderr)
  243.         return None._communicate(input)
  244.  
  245.     
  246.     def poll(self):
  247.         return self._internal_poll()
  248.  
  249.     if mswindows:
  250.         
  251.         def _get_handles(self, stdin, stdout, stderr):
  252.             if stdin is None and stdout is None and stderr is None:
  253.                 return (None, None, None, None, None, None)
  254.             (p2cread, p2cwrite) = None
  255.             (c2pread, c2pwrite) = (None, None)
  256.             (errread, errwrite) = (None, None)
  257.             if stdin is None:
  258.                 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
  259.                 if p2cread is None:
  260.                     (p2cread, _) = _subprocess.CreatePipe(None, 0)
  261.                 
  262.             elif stdin == PIPE:
  263.                 (p2cread, p2cwrite) = _subprocess.CreatePipe(None, 0)
  264.             elif isinstance(stdin, int):
  265.                 p2cread = msvcrt.get_osfhandle(stdin)
  266.             else:
  267.                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
  268.             p2cread = self._make_inheritable(p2cread)
  269.             if stdout is None:
  270.                 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
  271.                 if c2pwrite is None:
  272.                     (_, c2pwrite) = _subprocess.CreatePipe(None, 0)
  273.                 
  274.             elif stdout == PIPE:
  275.                 (c2pread, c2pwrite) = _subprocess.CreatePipe(None, 0)
  276.             elif isinstance(stdout, int):
  277.                 c2pwrite = msvcrt.get_osfhandle(stdout)
  278.             else:
  279.                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  280.             c2pwrite = self._make_inheritable(c2pwrite)
  281.             if stderr is None:
  282.                 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
  283.                 if errwrite is None:
  284.                     (_, errwrite) = _subprocess.CreatePipe(None, 0)
  285.                 
  286.             elif stderr == PIPE:
  287.                 (errread, errwrite) = _subprocess.CreatePipe(None, 0)
  288.             elif stderr == STDOUT:
  289.                 errwrite = c2pwrite
  290.             elif isinstance(stderr, int):
  291.                 errwrite = msvcrt.get_osfhandle(stderr)
  292.             else:
  293.                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
  294.             errwrite = self._make_inheritable(errwrite)
  295.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  296.  
  297.         
  298.         def _make_inheritable(self, handle):
  299.             return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), handle, _subprocess.GetCurrentProcess(), 0, 1, _subprocess.DUPLICATE_SAME_ACCESS)
  300.  
  301.         
  302.         def _find_w9xpopen(self):
  303.             w9xpopen = os.path.join(os.path.dirname(_subprocess.GetModuleFileName(0)), 'w9xpopen.exe')
  304.             if not os.path.exists(w9xpopen):
  305.                 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), 'w9xpopen.exe')
  306.                 if not os.path.exists(w9xpopen):
  307.                     raise RuntimeError('Cannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.')
  308.             return w9xpopen
  309.  
  310.         
  311.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  312.             if not isinstance(args, types.StringTypes):
  313.                 args = list2cmdline(args)
  314.             if startupinfo is None:
  315.                 startupinfo = STARTUPINFO()
  316.             if None not in (p2cread, c2pwrite, errwrite):
  317.                 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
  318.                 startupinfo.hStdInput = p2cread
  319.                 startupinfo.hStdOutput = c2pwrite
  320.                 startupinfo.hStdError = errwrite
  321.             if shell:
  322.                 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
  323.                 startupinfo.wShowWindow = _subprocess.SW_HIDE
  324.                 comspec = os.environ.get('COMSPEC', 'cmd.exe')
  325.                 args = '{} /c "{}"'.format(comspec, args)
  326.                 if _subprocess.GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == 'command.com':
  327.                     w9xpopen = self._find_w9xpopen()
  328.                     args = '"%s" %s' % (w9xpopen, args)
  329.                     creationflags |= _subprocess.CREATE_NEW_CONSOLE
  330.                 
  331.             
  332.             try:
  333.                 (hp, ht, pid, tid) = _subprocess.CreateProcess(executable, args, None, None, int(not close_fds), creationflags, env, cwd, startupinfo)
  334.             except pywintypes.error:
  335.                 startupinfo
  336.                 e = startupinfo
  337.                 startupinfo
  338.                 raise WindowsError(*e.args)
  339.             finally:
  340.                 if p2cread is not None:
  341.                     p2cread.Close()
  342.                 if c2pwrite is not None:
  343.                     c2pwrite.Close()
  344.                 if errwrite is not None:
  345.                     errwrite.Close()
  346.  
  347.             self._child_created = True
  348.             self._handle = hp
  349.             self.pid = pid
  350.             ht.Close()
  351.  
  352.         
  353.         def _internal_poll(self, _deadstate = None, _WaitForSingleObject = _subprocess.WaitForSingleObject, _WAIT_OBJECT_0 = _subprocess.WAIT_OBJECT_0, _GetExitCodeProcess = _subprocess.GetExitCodeProcess):
  354.             if self.returncode is None and _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
  355.                 self.returncode = _GetExitCodeProcess(self._handle)
  356.             
  357.             return self.returncode
  358.  
  359.         
  360.         def wait(self):
  361.             if self.returncode is None:
  362.                 _subprocess.WaitForSingleObject(self._handle, _subprocess.INFINITE)
  363.                 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
  364.             return self.returncode
  365.  
  366.         
  367.         def _readerthread(self, fh, buffer):
  368.             buffer.append(fh.read())
  369.  
  370.         
  371.         def _communicate(self, input):
  372.             stdout = None
  373.             stderr = None
  374.             if self.stdout:
  375.                 stdout = []
  376.                 stdout_thread = threading.Thread(target = self._readerthread, args = (self.stdout, stdout))
  377.                 stdout_thread.setDaemon(True)
  378.                 stdout_thread.start()
  379.             if self.stderr:
  380.                 stderr = []
  381.                 stderr_thread = threading.Thread(target = self._readerthread, args = (self.stderr, stderr))
  382.                 stderr_thread.setDaemon(True)
  383.                 stderr_thread.start()
  384.             if self.stdin:
  385.                 if input is not None:
  386.                     self.stdin.write(input)
  387.                 self.stdin.close()
  388.             if self.stdout:
  389.                 stdout_thread.join()
  390.             if self.stderr:
  391.                 stderr_thread.join()
  392.             if stdout is not None:
  393.                 stdout = stdout[0]
  394.             if stderr is not None:
  395.                 stderr = stderr[0]
  396.             if self.universal_newlines and hasattr(file, 'newlines'):
  397.                 if stdout:
  398.                     stdout = self._translate_newlines(stdout)
  399.                 if stderr:
  400.                     stderr = self._translate_newlines(stderr)
  401.                 
  402.             self.wait()
  403.             return (stdout, stderr)
  404.  
  405.         
  406.         def send_signal(self, sig):
  407.             if sig == signal.SIGTERM:
  408.                 self.terminate()
  409.             elif sig == signal.CTRL_C_EVENT:
  410.                 os.kill(self.pid, signal.CTRL_C_EVENT)
  411.             elif sig == signal.CTRL_BREAK_EVENT:
  412.                 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  413.             else:
  414.                 raise ValueError('Unsupported signal: {}'.format(sig))
  415.  
  416.         
  417.         def terminate(self):
  418.             _subprocess.TerminateProcess(self._handle, 1)
  419.  
  420.         kill = terminate
  421.     else:
  422.         
  423.         def _get_handles(self, stdin, stdout, stderr):
  424.             (p2cread, p2cwrite) = (None, None)
  425.             (c2pread, c2pwrite) = (None, None)
  426.             (errread, errwrite) = (None, None)
  427.             if stdin is None:
  428.                 pass
  429.             elif stdin == PIPE:
  430.                 (p2cread, p2cwrite) = os.pipe()
  431.             elif isinstance(stdin, int):
  432.                 p2cread = stdin
  433.             else:
  434.                 p2cread = stdin.fileno()
  435.             if stdout is None:
  436.                 pass
  437.             elif stdout == PIPE:
  438.                 (c2pread, c2pwrite) = os.pipe()
  439.             elif isinstance(stdout, int):
  440.                 c2pwrite = stdout
  441.             else:
  442.                 c2pwrite = stdout.fileno()
  443.             if stderr is None:
  444.                 pass
  445.             elif stderr == PIPE:
  446.                 (errread, errwrite) = os.pipe()
  447.             elif stderr == STDOUT:
  448.                 errwrite = c2pwrite
  449.             elif isinstance(stderr, int):
  450.                 errwrite = stderr
  451.             else:
  452.                 errwrite = stderr.fileno()
  453.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  454.  
  455.         
  456.         def _set_cloexec_flag(self, fd):
  457.             
  458.             try:
  459.                 cloexec_flag = fcntl.FD_CLOEXEC
  460.             except AttributeError:
  461.                 cloexec_flag = 1
  462.  
  463.             old = fcntl.fcntl(fd, fcntl.F_GETFD)
  464.             fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  465.  
  466.         
  467.         def _close_fds(self, but):
  468.             if hasattr(os, 'closerange'):
  469.                 os.closerange(3, but)
  470.                 os.closerange(but + 1, MAXFD)
  471.             else:
  472.                 for i in xrange(3, MAXFD):
  473.                     if i == but:
  474.                         continue
  475.                     
  476.                     try:
  477.                         os.close(i)
  478.                     continue
  479.                     continue
  480.  
  481.                 
  482.  
  483.         
  484.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  485.             if isinstance(args, types.StringTypes):
  486.                 args = [
  487.                     args]
  488.             else:
  489.                 args = list(args)
  490.             if shell:
  491.                 args = [
  492.                     '/bin/sh',
  493.                     '-c'] + args
  494.                 if executable:
  495.                     args[0] = executable
  496.                 
  497.             if executable is None:
  498.                 executable = args[0]
  499.             (errpipe_read, errpipe_write) = os.pipe()
  500.             
  501.             try:
  502.                 
  503.                 try:
  504.                     self._set_cloexec_flag(errpipe_write)
  505.                     gc_was_enabled = gc.isenabled()
  506.                     gc.disable()
  507.                     
  508.                     try:
  509.                         self.pid = os.fork()
  510.                     except:
  511.                         if gc_was_enabled:
  512.                             gc.enable()
  513.                         raise 
  514.  
  515.                     self._child_created = True
  516.                     if self.pid == 0:
  517.                         
  518.                         try:
  519.                             if p2cwrite is not None:
  520.                                 os.close(p2cwrite)
  521.                             if c2pread is not None:
  522.                                 os.close(c2pread)
  523.                             if errread is not None:
  524.                                 os.close(errread)
  525.                             os.close(errpipe_read)
  526.                             if p2cread is not None:
  527.                                 os.dup2(p2cread, 0)
  528.                             if c2pwrite is not None:
  529.                                 os.dup2(c2pwrite, 1)
  530.                             if errwrite is not None:
  531.                                 os.dup2(errwrite, 2)
  532.                             if p2cread is not None and p2cread not in (0,):
  533.                                 os.close(p2cread)
  534.                             if c2pwrite is not None and c2pwrite not in (p2cread, 1):
  535.                                 os.close(c2pwrite)
  536.                             if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
  537.                                 os.close(errwrite)
  538.                             if close_fds:
  539.                                 self._close_fds(but = errpipe_write)
  540.                             if cwd is not None:
  541.                                 os.chdir(cwd)
  542.                             if preexec_fn:
  543.                                 preexec_fn()
  544.                             if env is None:
  545.                                 os.execvp(executable, args)
  546.                             else:
  547.                                 os.execvpe(executable, args, env)
  548.                         except:
  549.                             (exc_type, exc_value, tb) = sys.exc_info()
  550.                             exc_lines = traceback.format_exception(exc_type, exc_value, tb)
  551.                             exc_value.child_traceback = ''.join(exc_lines)
  552.                             os.write(errpipe_write, pickle.dumps(exc_value))
  553.  
  554.                         os._exit(255)
  555.                     if gc_was_enabled:
  556.                         gc.enable()
  557.                 finally:
  558.                     os.close(errpipe_write)
  559.  
  560.                 if p2cread is not None and p2cwrite is not None:
  561.                     os.close(p2cread)
  562.                 if c2pwrite is not None and c2pread is not None:
  563.                     os.close(c2pwrite)
  564.                 if errwrite is not None and errread is not None:
  565.                     os.close(errwrite)
  566.                 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
  567.             finally:
  568.                 os.close(errpipe_read)
  569.  
  570.             if data != '':
  571.                 _eintr_retry_call(os.waitpid, self.pid, 0)
  572.                 child_exception = pickle.loads(data)
  573.                 for fd in (p2cwrite, c2pread, errread):
  574.                     if fd is not None:
  575.                         os.close(fd)
  576.                         continue
  577.                 raise child_exception
  578.  
  579.         
  580.         def _handle_exitstatus(self, sts, _WIFSIGNALED = os.WIFSIGNALED, _WTERMSIG = os.WTERMSIG, _WIFEXITED = os.WIFEXITED, _WEXITSTATUS = os.WEXITSTATUS):
  581.             if _WIFSIGNALED(sts):
  582.                 self.returncode = -_WTERMSIG(sts)
  583.             elif _WIFEXITED(sts):
  584.                 self.returncode = _WEXITSTATUS(sts)
  585.             else:
  586.                 raise RuntimeError('Unknown child exit status!')
  587.  
  588.         
  589.         def _internal_poll(self, _deadstate = None, _waitpid = os.waitpid, _WNOHANG = os.WNOHANG, _os_error = os.error):
  590.             if self.returncode is None:
  591.                 
  592.                 try:
  593.                     (pid, sts) = _waitpid(self.pid, _WNOHANG)
  594.                     if pid == self.pid:
  595.                         self._handle_exitstatus(sts)
  596.                 except _os_error:
  597.                     if _deadstate is not None:
  598.                         self.returncode = _deadstate
  599.                     
  600.                 
  601.  
  602.             return self.returncode
  603.  
  604.         
  605.         def wait(self):
  606.             if self.returncode is None:
  607.                 (pid, sts) = _eintr_retry_call(os.waitpid, self.pid, 0)
  608.                 self._handle_exitstatus(sts)
  609.             return self.returncode
  610.  
  611.         
  612.         def _communicate(self, input):
  613.             if self.stdin:
  614.                 self.stdin.flush()
  615.                 if not input:
  616.                     self.stdin.close()
  617.                 
  618.             if _has_poll:
  619.                 (stdout, stderr) = self._communicate_with_poll(input)
  620.             else:
  621.                 (stdout, stderr) = self._communicate_with_select(input)
  622.             if stdout is not None:
  623.                 stdout = ''.join(stdout)
  624.             if stderr is not None:
  625.                 stderr = ''.join(stderr)
  626.             if self.universal_newlines and hasattr(file, 'newlines'):
  627.                 if stdout:
  628.                     stdout = self._translate_newlines(stdout)
  629.                 if stderr:
  630.                     stderr = self._translate_newlines(stderr)
  631.                 
  632.             self.wait()
  633.             return (stdout, stderr)
  634.  
  635.         
  636.         def _communicate_with_poll(self, input):
  637.             stdout = None
  638.             stderr = None
  639.             fd2file = { }
  640.             fd2output = { }
  641.             poller = select.poll()
  642.             
  643.             def register_and_append(file_obj, eventmask):
  644.                 poller.register(file_obj.fileno(), eventmask)
  645.                 fd2file[file_obj.fileno()] = file_obj
  646.  
  647.             
  648.             def close_unregister_and_remove(fd):
  649.                 poller.unregister(fd)
  650.                 fd2file[fd].close()
  651.                 fd2file.pop(fd)
  652.  
  653.             if self.stdin and input:
  654.                 register_and_append(self.stdin, select.POLLOUT)
  655.             select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
  656.             if self.stdout:
  657.                 register_and_append(self.stdout, select_POLLIN_POLLPRI)
  658.             if self.stderr:
  659.                 register_and_append(self.stderr, select_POLLIN_POLLPRI)
  660.             input_offset = 0
  661.             while fd2file:
  662.                 
  663.                 try:
  664.                     ready = poller.poll()
  665.                 except select.error:
  666.                     fd2output[self.stdout.fileno()] = stdout = e = []
  667.                     fd2output[self.stdout.fileno()] = stdout = e = []
  668.                     if e.args[0] == errno.EINTR:
  669.                         continue
  670.                     raise 
  671.  
  672.                 for fd, mode in ready:
  673.                     if mode & select.POLLOUT:
  674.                         chunk = input[input_offset:input_offset + _PIPE_BUF]
  675.                         input_offset += os.write(fd, chunk)
  676.                         if input_offset >= len(input):
  677.                             close_unregister_and_remove(fd)
  678.                         
  679.                     if mode & select_POLLIN_POLLPRI:
  680.                         data = os.read(fd, 4096)
  681.                         if not data:
  682.                             close_unregister_and_remove(fd)
  683.                         fd2output[fd].append(data)
  684.                         continue
  685.                     close_unregister_and_remove(fd)
  686.                 
  687.             return (stdout, stderr)
  688.  
  689.         
  690.         def _communicate_with_select(self, input):
  691.             read_set = []
  692.             write_set = []
  693.             stdout = None
  694.             stderr = None
  695.             if self.stdin and input:
  696.                 write_set.append(self.stdin)
  697.             if self.stdout:
  698.                 read_set.append(self.stdout)
  699.                 stdout = []
  700.             if self.stderr:
  701.                 read_set.append(self.stderr)
  702.                 stderr = []
  703.             input_offset = 0
  704.             while read_set or write_set:
  705.                 
  706.                 try:
  707.                     (rlist, wlist, xlist) = select.select(read_set, write_set, [])
  708.                 except select.error:
  709.                     e = None
  710.                     if e.args[0] == errno.EINTR:
  711.                         continue
  712.                     raise 
  713.  
  714.                 if self.stdin in wlist:
  715.                     chunk = input[input_offset:input_offset + _PIPE_BUF]
  716.                     bytes_written = os.write(self.stdin.fileno(), chunk)
  717.                     input_offset += bytes_written
  718.                     if input_offset >= len(input):
  719.                         self.stdin.close()
  720.                         write_set.remove(self.stdin)
  721.                     
  722.                 if self.stdout in rlist:
  723.                     data = os.read(self.stdout.fileno(), 1024)
  724.                     if data == '':
  725.                         self.stdout.close()
  726.                         read_set.remove(self.stdout)
  727.                     stdout.append(data)
  728.                 if self.stderr in rlist:
  729.                     data = os.read(self.stderr.fileno(), 1024)
  730.                     if data == '':
  731.                         self.stderr.close()
  732.                         read_set.remove(self.stderr)
  733.                     stderr.append(data)
  734.                     continue
  735.                 return (stdout, stderr)
  736.  
  737.         
  738.         def send_signal(self, sig):
  739.             os.kill(self.pid, sig)
  740.  
  741.         
  742.         def terminate(self):
  743.             self.send_signal(signal.SIGTERM)
  744.  
  745.         
  746.         def kill(self):
  747.             self.send_signal(signal.SIGKILL)
  748.  
  749.  
  750.  
  751. def _demo_posix():
  752.     plist = Popen([
  753.         'ps'], stdout = PIPE).communicate()[0]
  754.     print 'Process list:'
  755.     print plist
  756.     if os.getuid() == 0:
  757.         p = Popen([
  758.             'id'], preexec_fn = (lambda : os.setuid(100)))
  759.         p.wait()
  760.     print "Looking for 'hda'..."
  761.     p1 = Popen([
  762.         'dmesg'], stdout = PIPE)
  763.     p2 = Popen([
  764.         'grep',
  765.         'hda'], stdin = p1.stdout, stdout = PIPE)
  766.     print repr(p2.communicate()[0])
  767.     print 
  768.     print 'Trying a weird file...'
  769.     
  770.     try:
  771.         print Popen([
  772.             '/this/path/does/not/exist']).communicate()
  773.     except OSError:
  774.         e = None
  775.         if e.errno == errno.ENOENT:
  776.             print "The file didn't exist.  I thought so..."
  777.             print 'Child traceback:'
  778.             print e.child_traceback
  779.         else:
  780.             print 'Error', e.errno
  781.  
  782.     print >>sys.stderr, 'Gosh.  No error.'
  783.  
  784.  
  785. def _demo_windows():
  786.     print "Looking for 'PROMPT' in set output..."
  787.     p1 = Popen('set', stdout = PIPE, shell = True)
  788.     p2 = Popen('find "PROMPT"', stdin = p1.stdout, stdout = PIPE)
  789.     print repr(p2.communicate()[0])
  790.     print 'Executing calc...'
  791.     p = Popen('calc')
  792.     p.wait()
  793.  
  794. if __name__ == '__main__':
  795.     if mswindows:
  796.         _demo_windows()
  797.     else:
  798.         _demo_posix()
  799.