home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / hplip / base / pexpect.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  50.9 KB  |  1,470 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Pexpect is a Python module for spawning child applications and controlling
  5. them automatically. Pexpect can be used for automating interactive applications
  6. such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
  7. scripts for duplicating software package installations on different servers. It
  8. can be used for automated software testing. Pexpect is in the spirit of Don
  9. Libes\' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
  10. require TCL and Expect or require C extensions to be compiled. Pexpect does not
  11. use C, Expect, or TCL extensions. It should work on any platform that supports
  12. the standard Python pty module. The Pexpect interface focuses on ease of use so
  13. that simple tasks are easy.
  14.  
  15. There are two main interfaces to Pexpect -- the function, run() and the class,
  16. spawn. You can call the run() function to execute a command and return the
  17. output. This is a handy replacement for os.system().
  18.  
  19. For example:
  20.     pexpect.run(\'ls -la\')
  21.  
  22. The more powerful interface is the spawn class. You can use this to spawn an
  23. external child command and then interact with the child by sending lines and
  24. expecting responses.
  25.  
  26. For example:
  27.     child = pexpect.spawn(\'scp foo myname@host.example.com:.\')
  28.     child.expect (\'Password:\')
  29.     child.sendline (mypassword)
  30.  
  31. This works even for commands that ask for passwords or other input outside of
  32. the normal stdio streams.
  33.  
  34. Credits:
  35. Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, Robert Stone,
  36. Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids vander Molen,
  37. George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
  38. Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy,
  39. Fernando Perez 
  40. (Let me know if I forgot anyone.)
  41.  
  42. Free, open source, and all that good stuff.
  43.  
  44. Permission is hereby granted, free of charge, to any person obtaining a copy of
  45. this software and associated documentation files (the "Software"), to deal in
  46. the Software without restriction, including without limitation the rights to
  47. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  48. of the Software, and to permit persons to whom the Software is furnished to do
  49. so, subject to the following conditions:
  50.  
  51. The above copyright notice and this permission notice shall be included in all
  52. copies or substantial portions of the Software.
  53.  
  54. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  55. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  56. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  57. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  58. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  59. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  60. SOFTWARE.
  61.  
  62. Pexpect Copyright (c) 2006 Noah Spurrier
  63. http://pexpect.sourceforge.net/
  64.  
  65. $Revision: 1.2 $
  66. $Date: 2007/01/11 20:51:46 $
  67. '''
  68.  
  69. try:
  70.     import os
  71.     import sys
  72.     import time
  73.     import select
  74.     import string
  75.     import re
  76.     import struct
  77.     import resource
  78.     import types
  79.     import pty
  80.     import tty
  81.     import termios
  82.     import fcntl
  83.     import errno
  84.     import traceback
  85.     import signal
  86. except ImportError:
  87.     e = None
  88.     raise ImportError(str(e) + '\nA critical module was not found. Probably this operating system does not support it.\nPexpect is intended for UNIX-like operating systems.')
  89.  
  90. __version__ = '2.1'
  91. __revision__ = '$Revision: 1.2 $'
  92. __all__ = [
  93.     'ExceptionPexpect',
  94.     'EOF',
  95.     'TIMEOUT',
  96.     'spawn',
  97.     'run',
  98.     'which',
  99.     'split_command_line',
  100.     '__version__',
  101.     '__revision__']
  102.  
  103. class ExceptionPexpect(Exception):
  104.     '''Base class for all exceptions raised by this module.
  105.     '''
  106.     
  107.     def __init__(self, value):
  108.         self.value = value
  109.  
  110.     
  111.     def __str__(self):
  112.         return str(self.value)
  113.  
  114.     
  115.     def get_trace(self):
  116.         '''This returns an abbreviated stack trace with lines that only concern the caller.
  117.         In other words, the stack trace inside the Pexpect module is not included.
  118.         '''
  119.         tblist = traceback.extract_tb(sys.exc_info()[2])
  120.         tblist = filter(self._ExceptionPexpect__filter_not_pexpect, tblist)
  121.         tblist = traceback.format_list(tblist)
  122.         return ''.join(tblist)
  123.  
  124.     
  125.     def __filter_not_pexpect(self, trace_list_item):
  126.         if trace_list_item[0].find('pexpect.py') == -1:
  127.             return True
  128.         else:
  129.             return False
  130.  
  131.  
  132.  
  133. class EOF(ExceptionPexpect):
  134.     '''Raised when EOF is read from a child.
  135.     '''
  136.     pass
  137.  
  138.  
  139. class TIMEOUT(ExceptionPexpect):
  140.     '''Raised when a read time exceeds the timeout.
  141.     '''
  142.     pass
  143.  
  144.  
  145. def run(command, timeout = -1, withexitstatus = False, events = None, extra_args = None, logfile = None):
  146.     '''This function runs the given command; waits for it to finish;
  147.     then returns all output as a string. STDERR is included in output.
  148.     If the full path to the command is not given then the path is searched.
  149.  
  150.     Note that lines are terminated by CR/LF (\\r\\n) combination
  151.     even on UNIX-like systems because this is the standard for pseudo ttys.
  152.     If you set withexitstatus to true, then run will return a tuple of
  153.     (command_output, exitstatus). If withexitstatus is false then this
  154.     returns just command_output.
  155.  
  156.     The run() function can often be used instead of creating a spawn instance.
  157.     For example, the following code uses spawn:
  158.         from pexpect import *
  159.         child = spawn(\'scp foo myname@host.example.com:.\')
  160.         child.expect (\'(?i)password\')
  161.         child.sendline (mypassword)
  162.     The previous code can be replace with the following, which you may
  163.     or may not find simpler:
  164.         from pexpect import *
  165.         run (\'scp foo myname@host.example.com:.\', events={\'(?i)password\': mypassword})
  166.  
  167.     Examples:
  168.     Start the apache daemon on the local machine:
  169.         from pexpect import *
  170.         run ("/usr/local/apache/bin/apachectl start")
  171.     Check in a file using SVN:
  172.         from pexpect import *
  173.         run ("svn ci -m \'automatic commit\' my_file.py")
  174.     Run a command and capture exit status:
  175.         from pexpect import *
  176.         (command_output, exitstatus) = run (\'ls -l /bin\', withexitstatus=1)
  177.  
  178.     Tricky Examples:   
  179.     The following will run SSH and execute \'ls -l\' on the remote machine.
  180.     The password \'secret\' will be sent if the \'(?i)password\' pattern is ever seen.
  181.         run ("ssh username@machine.example.com \'ls -l\'", events={\'(?i)password\':\'secret
  182. \'})
  183.  
  184.     This will start mencoder to rip a video from DVD. This will also display
  185.     progress ticks every 5 seconds as it runs.
  186.         from pexpect import *
  187.         def print_ticks(d):
  188.             print d[\'event_count\'],
  189.         run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5)
  190.  
  191.     The \'events\' argument should be a dictionary of patterns and responses.
  192.     Whenever one of the patterns is seen in the command out
  193.     run() will send the associated response string. Note that you should
  194.     put newlines in your string if Enter is necessary.
  195.     The responses may also contain callback functions.
  196.     Any callback is function that takes a dictionary as an argument.
  197.     The dictionary contains all the locals from the run() function, so
  198.     you can access the child spawn object or any other variable defined
  199.     in run() (event_count, child, and extra_args are the most useful).
  200.     A callback may return True to stop the current run process otherwise
  201.     run() continues until the next event.
  202.     A callback may also return a string which will be sent to the child.
  203.     \'extra_args\' is not used by directly run(). It provides a way to pass data to
  204.     a callback function through run() through the locals dictionary passed to a callback.
  205.     '''
  206.     if timeout == -1:
  207.         child = spawn(command, maxread = 2000, logfile = logfile)
  208.     else:
  209.         child = spawn(command, timeout = timeout, maxread = 2000, logfile = logfile)
  210.     if events is not None:
  211.         patterns = events.keys()
  212.         responses = events.values()
  213.     else:
  214.         patterns = None
  215.         responses = None
  216.     child_result_list = []
  217.     event_count = 0
  218.     while None:
  219.         
  220.         try:
  221.             index = child.expect(patterns)
  222.             if type(child.after) is types.StringType:
  223.                 child_result_list.append(child.before + child.after)
  224.             else:
  225.                 child_result_list.append(child.before)
  226.             if type(responses[index]) is types.StringType:
  227.                 child.send(responses[index])
  228.             elif type(responses[index]) is types.FunctionType:
  229.                 callback_result = responses[index](locals())
  230.                 sys.stdout.flush()
  231.                 if type(callback_result) is types.StringType:
  232.                     child.send(callback_result)
  233.                 elif callback_result:
  234.                     break
  235.                 
  236.             else:
  237.                 raise TypeError('The callback must be a string or function type.')
  238.             event_count = event_count + 1
  239.         continue
  240.         except TIMEOUT:
  241.             e = None
  242.             child_result_list.append(child.before)
  243.             break
  244.             continue
  245.             except EOF:
  246.                 e = None
  247.                 child_result_list.append(child.before)
  248.                 break
  249.                 continue
  250.             
  251.             child_result = ''.join(child_result_list)
  252.             if withexitstatus:
  253.                 child.close()
  254.                 return (child_result, child.exitstatus)
  255.             else:
  256.                 return child_result
  257.  
  258.  
  259.  
  260. class spawn(object):
  261.     '''This is the main class interface for Pexpect.
  262.     Use this class to start and control child applications.
  263.     '''
  264.     
  265.     def __init__(self, command, args = [], timeout = 30, maxread = 2000, searchwindowsize = None, logfile = None, env = None):
  266.         '''This is the constructor. The command parameter may be a string
  267.         that includes a command and any arguments to the command. For example:
  268.             p = pexpect.spawn (\'/usr/bin/ftp\')
  269.             p = pexpect.spawn (\'/usr/bin/ssh user@example.com\')
  270.             p = pexpect.spawn (\'ls -latr /tmp\')
  271.         You may also construct it with a list of arguments like so:
  272.             p = pexpect.spawn (\'/usr/bin/ftp\', [])
  273.             p = pexpect.spawn (\'/usr/bin/ssh\', [\'user@example.com\'])
  274.             p = pexpect.spawn (\'ls\', [\'-latr\', \'/tmp\'])
  275.         After this the child application will be created and
  276.         will be ready to talk to. For normal use, see expect() and 
  277.         send() and sendline().
  278.  
  279.         The maxread attribute sets the read buffer size.
  280.         This is maximum number of bytes that Pexpect will try to read
  281.         from a TTY at one time.
  282.         Seeting the maxread size to 1 will turn off buffering.
  283.         Setting the maxread value higher may help performance in cases
  284.         where large amounts of output are read back from the child.
  285.         This feature is useful in conjunction with searchwindowsize.
  286.  
  287.         The searchwindowsize attribute sets the how far back in
  288.         the incomming seach buffer Pexpect will search for pattern matches.
  289.         Every time Pexpect reads some data from the child it will append the data to
  290.         the incomming buffer. The default is to search from the beginning of the
  291.         imcomming buffer each time new data is read from the child.
  292.         But this is very inefficient if you are running a command that
  293.         generates a large amount of data where you want to match
  294.         The searchwindowsize does not effect the size of the incomming data buffer.
  295.         You will still have access to the full buffer after expect() returns.
  296.  
  297.         The logfile member turns on or off logging.
  298.         All input and output will be copied to the given file object.
  299.         Set logfile to None to stop logging. This is the default.
  300.         Set logfile to sys.stdout to echo everything to standard output.
  301.         The logfile is flushed after each write.
  302.         Example 1:
  303.             child = pexpect.spawn(\'some_command\')
  304.             fout = file(\'mylog.txt\',\'w\')
  305.             child.logfile = fout
  306.         Example 2:
  307.             child = pexpect.spawn(\'some_command\')
  308.             child.logfile = sys.stdout
  309.  
  310.         The delaybeforesend helps overcome a weird behavior that many users were experiencing.
  311.         The typical problem was that a user would expect() a "Password:" prompt and
  312.         then immediately call sendline() to send the password. The user would then
  313.         see that their password was echoed back to them. Passwords don\'t
  314.         normally echo. The problem is caused by the fact that most applications
  315.         print out the "Password" prompt and then turn off stdin echo, but if you
  316.         send your password before the application turned off echo, then you get
  317.         your password echoed. Normally this wouldn\'t be a problem when interacting
  318.         with a human at a real heyboard. If you introduce a slight delay just before 
  319.         writing then this seems to clear up the problem. This was such a common problem 
  320.         for many users that I decided that the default pexpect behavior
  321.         should be to sleep just before writing to the child application.
  322.         1/10th of a second (100 ms) seems to be enough to clear up the problem.
  323.         You can set delaybeforesend to 0 to return to the old behavior.
  324.  
  325.         Note that spawn is clever about finding commands on your path.
  326.         It uses the same logic that "which" uses to find executables.
  327.  
  328.         If you wish to get the exit status of the child you must call
  329.         the close() method. The exit or signal status of the child will be
  330.         stored in self.exitstatus or self.signalstatus.
  331.         If the child exited normally then exitstatus will store the exit return code and
  332.         signalstatus will be None.
  333.         If the child was terminated abnormally with a signal then signalstatus will store
  334.         the signal value and exitstatus will be None.
  335.         If you need more detail you can also read the self.status member which stores
  336.         the status returned by os.waitpid. You can interpret this using
  337.         os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
  338.         '''
  339.         self.STDIN_FILENO = pty.STDIN_FILENO
  340.         self.STDOUT_FILENO = pty.STDOUT_FILENO
  341.         self.STDERR_FILENO = pty.STDERR_FILENO
  342.         self.stdin = sys.stdin
  343.         self.stdout = sys.stdout
  344.         self.stderr = sys.stderr
  345.         self.patterns = None
  346.         self.ignorecase = False
  347.         self.before = None
  348.         self.after = None
  349.         self.match = None
  350.         self.match_index = None
  351.         self.terminated = True
  352.         self.exitstatus = None
  353.         self.signalstatus = None
  354.         self.status = None
  355.         self.flag_eof = False
  356.         self.pid = None
  357.         self.child_fd = -1
  358.         self.timeout = timeout
  359.         self.delimiter = EOF
  360.         self.logfile = logfile
  361.         self.maxread = maxread
  362.         self.buffer = ''
  363.         self.searchwindowsize = searchwindowsize
  364.         self.delaybeforesend = 0.1
  365.         self.delayafterclose = 0.1
  366.         self.delayafterterminate = 0.1
  367.         self.softspace = False
  368.         self.name = '<' + repr(self) + '>'
  369.         self.encoding = None
  370.         self.closed = True
  371.         self.env = env
  372.         self._spawn__irix_hack = sys.platform.lower().find('irix') >= 0
  373.         self.use_native_pty_fork = not (sys.platform.lower().find('solaris') >= 0)
  374.         if command is None:
  375.             self.command = None
  376.             self.args = None
  377.             self.name = '<pexpect factory incomplete>'
  378.             return None
  379.         
  380.         if type(command) == type(0):
  381.             raise ExceptionPexpect('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.')
  382.         
  383.         if type(args) != type([]):
  384.             raise TypeError('The argument, args, must be a list.')
  385.         
  386.         if args == []:
  387.             self.args = split_command_line(command)
  388.             self.command = self.args[0]
  389.         else:
  390.             self.args = args[:]
  391.             self.args.insert(0, command)
  392.             self.command = command
  393.         command_with_path = which(self.command)
  394.         if command_with_path is None:
  395.             raise ExceptionPexpect('The command was not found or was not executable: %s.' % self.command)
  396.         
  397.         self.command = command_with_path
  398.         self.args[0] = self.command
  399.         self.name = '<' + ' '.join(self.args) + '>'
  400.         self._spawn__spawn()
  401.  
  402.     
  403.     def __del__(self):
  404.         '''This makes sure that no system resources are left open.
  405.         Python only garbage collects Python objects. OS file descriptors
  406.         are not Python objects, so they must be handled explicitly.
  407.         If the child file descriptor was opened outside of this class
  408.         (passed to the constructor) then this does not close it.
  409.         '''
  410.         if not self.closed:
  411.             self.close()
  412.         
  413.  
  414.     
  415.     def __str__(self):
  416.         '''This returns the current state of the pexpect object as a string.
  417.         '''
  418.         s = []
  419.         s.append(repr(self))
  420.         s.append('version: ' + __version__ + ' (' + __revision__ + ')')
  421.         s.append('command: ' + str(self.command))
  422.         s.append('args: ' + str(self.args))
  423.         if self.patterns is None:
  424.             s.append('patterns: None')
  425.         else:
  426.             s.append('patterns:')
  427.             for p in self.patterns:
  428.                 if type(p) is type(re.compile('')):
  429.                     s.append('    ' + str(p.pattern))
  430.                     continue
  431.                 s.append('    ' + str(p))
  432.             
  433.         s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
  434.         s.append('before (last 100 chars): ' + str(self.before)[-100:])
  435.         s.append('after: ' + str(self.after))
  436.         s.append('match: ' + str(self.match))
  437.         s.append('match_index: ' + str(self.match_index))
  438.         s.append('exitstatus: ' + str(self.exitstatus))
  439.         s.append('flag_eof: ' + str(self.flag_eof))
  440.         s.append('pid: ' + str(self.pid))
  441.         s.append('child_fd: ' + str(self.child_fd))
  442.         s.append('closed: ' + str(self.closed))
  443.         s.append('timeout: ' + str(self.timeout))
  444.         s.append('delimiter: ' + str(self.delimiter))
  445.         s.append('logfile: ' + str(self.logfile))
  446.         s.append('maxread: ' + str(self.maxread))
  447.         s.append('ignorecase: ' + str(self.ignorecase))
  448.         s.append('searchwindowsize: ' + str(self.searchwindowsize))
  449.         s.append('delaybeforesend: ' + str(self.delaybeforesend))
  450.         s.append('delayafterclose: ' + str(self.delayafterclose))
  451.         s.append('delayafterterminate: ' + str(self.delayafterterminate))
  452.         return '\n'.join(s)
  453.  
  454.     
  455.     def __spawn(self):
  456.         '''This starts the given command in a child process.
  457.         This does all the fork/exec type of stuff for a pty.
  458.         This is called by __init__. 
  459.         '''
  460.         if not self.pid is None:
  461.             raise AssertionError, 'The pid member should be None.'
  462.         if not self.command is not None:
  463.             raise AssertionError, 'The command member should not be None.'
  464.         if self.use_native_pty_fork:
  465.             
  466.             try:
  467.                 (self.pid, self.child_fd) = pty.fork()
  468.             except OSError:
  469.                 e = None
  470.                 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
  471.             except:
  472.                 None<EXCEPTION MATCH>OSError
  473.             
  474.  
  475.         None<EXCEPTION MATCH>OSError
  476.         (self.pid, self.child_fd) = self._spawn__fork_pty()
  477.         if self.pid == 0:
  478.             
  479.             try:
  480.                 self.child_fd = sys.stdout.fileno()
  481.                 self.setwinsize(24, 80)
  482.             except:
  483.                 pass
  484.  
  485.             max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
  486.             for i in range(3, max_fd):
  487.                 
  488.                 try:
  489.                     os.close(i)
  490.                 continue
  491.                 except OSError:
  492.                     continue
  493.                 
  494.  
  495.             
  496.             signal.signal(signal.SIGHUP, signal.SIG_IGN)
  497.             if self.env is None:
  498.                 os.execv(self.command, self.args)
  499.             else:
  500.                 os.execvpe(self.command, self.args, self.env)
  501.         
  502.         self.terminated = False
  503.         self.closed = False
  504.  
  505.     
  506.     def __fork_pty(self):
  507.         """This implements a substitute for the forkpty system call.
  508.         This should be more portable than the pty.fork() function.
  509.         Specifically, this should work on Solaris.
  510.  
  511.         Modified 10.06.05 by Geoff Marshall:
  512.             Implemented __fork_pty() method to resolve the issue with Python's 
  513.             pty.fork() not supporting Solaris, particularly ssh.
  514.         Based on patch to posixmodule.c authored by Noah Spurrier:
  515.             http://mail.python.org/pipermail/python-dev/2003-May/035281.html
  516.         """
  517.         (parent_fd, child_fd) = os.openpty()
  518.         if parent_fd < 0 or child_fd < 0:
  519.             raise ExceptionPexpect, 'Error! Could not open pty with os.openpty().'
  520.         
  521.         pid = os.fork()
  522.         if pid < 0:
  523.             raise ExceptionPexpect, 'Error! Failed os.fork().'
  524.         elif pid == 0:
  525.             os.close(parent_fd)
  526.             self._spawn__pty_make_controlling_tty(child_fd)
  527.             os.dup2(child_fd, 0)
  528.             os.dup2(child_fd, 1)
  529.             os.dup2(child_fd, 2)
  530.             if child_fd > 2:
  531.                 os.close(child_fd)
  532.             
  533.         else:
  534.             os.close(child_fd)
  535.         return (pid, parent_fd)
  536.  
  537.     
  538.     def __pty_make_controlling_tty(self, tty_fd):
  539.         '''This makes the pseudo-terminal the controlling tty.
  540.         This should be more portable than the pty.fork() function.
  541.         Specifically, this should work on Solaris.
  542.         '''
  543.         child_name = os.ttyname(tty_fd)
  544.         fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
  545.         if fd >= 0:
  546.             os.close(fd)
  547.         
  548.         os.setsid()
  549.         
  550.         try:
  551.             fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
  552.             if fd >= 0:
  553.                 os.close(fd)
  554.                 raise ExceptionPexpect, 'Error! We are not disconnected from a controlling tty.'
  555.         except:
  556.             pass
  557.  
  558.         fd = os.open(child_name, os.O_RDWR)
  559.         if fd < 0:
  560.             raise ExceptionPexpect, 'Error! Could not open child pty, ' + child_name
  561.         else:
  562.             os.close(fd)
  563.         fd = os.open('/dev/tty', os.O_WRONLY)
  564.         if fd < 0:
  565.             raise ExceptionPexpect, 'Error! Could not open controlling tty, /dev/tty'
  566.         else:
  567.             os.close(fd)
  568.  
  569.     
  570.     def fileno(self):
  571.         '''This returns the file descriptor of the pty for the child.
  572.         '''
  573.         return self.child_fd
  574.  
  575.     
  576.     def close(self, force = True):
  577.         '''This closes the connection with the child application.
  578.         Note that calling close() more than once is valid.
  579.         This emulates standard Python behavior with files.
  580.         Set force to True if you want to make sure that the child is terminated
  581.         (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
  582.         '''
  583.         if not self.closed:
  584.             self.flush()
  585.             os.close(self.child_fd)
  586.             self.child_fd = -1
  587.             self.closed = True
  588.             time.sleep(self.delayafterclose)
  589.             if self.isalive():
  590.                 if not self.terminate(force):
  591.                     raise ExceptionPexpect('close() could not terminate the child using terminate()')
  592.                 
  593.             
  594.         
  595.  
  596.     
  597.     def flush(self):
  598.         '''This does nothing. It is here to support the interface for a File-like object.
  599.         '''
  600.         pass
  601.  
  602.     
  603.     def isatty(self):
  604.         '''This returns True if the file descriptor is open and connected to a tty(-like) device, else False.
  605.         '''
  606.         return os.isatty(self.child_fd)
  607.  
  608.     
  609.     def setecho(self, state):
  610.         """This sets the terminal echo mode on or off.
  611.         Note that anything the child sent before the echo will be lost, so
  612.         you should be sure that your input buffer is empty before you setecho.
  613.         For example, the following will work as expected.
  614.             p = pexpect.spawn('cat')
  615.             p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
  616.             p.expect (['1234'])
  617.             p.expect (['1234'])
  618.             p.setecho(False) # Turn off tty echo
  619.             p.sendline ('abcd') # We will set this only once (echoed by cat).
  620.             p.sendline ('wxyz') # We will set this only once (echoed by cat)
  621.             p.expect (['abcd'])
  622.             p.expect (['wxyz'])
  623.         The following WILL NOT WORK because the lines sent before the setecho
  624.         will be lost:
  625.             p = pexpect.spawn('cat')
  626.             p.sendline ('1234') # We will see this twice (once from tty echo and again from cat).
  627.             p.setecho(False) # Turn off tty echo
  628.             p.sendline ('abcd') # We will set this only once (echoed by cat).
  629.             p.sendline ('wxyz') # We will set this only once (echoed by cat)
  630.             p.expect (['1234'])
  631.             p.expect (['1234'])
  632.             p.expect (['abcd'])
  633.             p.expect (['wxyz'])
  634.         """
  635.         self.child_fd
  636.         new = termios.tcgetattr(self.child_fd)
  637.         if state:
  638.             new[3] = new[3] | termios.ECHO
  639.         else:
  640.             new[3] = new[3] & ~(termios.ECHO)
  641.         termios.tcsetattr(self.child_fd, termios.TCSANOW, new)
  642.  
  643.     
  644.     def read_nonblocking(self, size = 1, timeout = -1):
  645.         '''This reads at most size characters from the child application.
  646.         It includes a timeout. If the read does not complete within the
  647.         timeout period then a TIMEOUT exception is raised.
  648.         If the end of file is read then an EOF exception will be raised.
  649.         If a log file was set using setlog() then all data will
  650.         also be written to the log file.
  651.  
  652.         If timeout==None then the read may block indefinitely.
  653.         If timeout==-1 then the self.timeout value is used.
  654.         If timeout==0 then the child is polled and 
  655.             if there was no data immediately ready then this will raise a TIMEOUT exception.
  656.  
  657.         The "timeout" refers only to the amount of time to read at least one character.
  658.         This is not effected by the \'size\' parameter, so if you call
  659.         read_nonblocking(size=100, timeout=30) and only one character is
  660.         available right away then one character will be returned immediately. 
  661.         It will not wait for 30 seconds for another 99 characters to come in.
  662.  
  663.         This is a wrapper around os.read().
  664.         It uses select.select() to implement a timeout. 
  665.         '''
  666.         if self.closed:
  667.             raise ValueError('I/O operation on closed file in read_nonblocking().')
  668.         
  669.         if timeout == -1:
  670.             timeout = self.timeout
  671.         
  672.         if not self.isalive():
  673.             (r, w, e) = self._spawn__select([
  674.                 self.child_fd], [], [], 0)
  675.             if not r:
  676.                 self.flag_eof = True
  677.                 raise EOF('End Of File (EOF) in read_nonblocking(). Braindead platform.')
  678.             
  679.         elif self._spawn__irix_hack:
  680.             (r, w, e) = self._spawn__select([
  681.                 self.child_fd], [], [], 2)
  682.             if not r and not self.isalive():
  683.                 self.flag_eof = True
  684.                 raise EOF('End Of File (EOF) in read_nonblocking(). Pokey platform.')
  685.             
  686.         
  687.         (r, w, e) = self._spawn__select([
  688.             self.child_fd], [], [], timeout)
  689.         if not r:
  690.             if not self.isalive():
  691.                 self.flag_eof = True
  692.                 raise EOF('End of File (EOF) in read_nonblocking(). Very pokey platform.')
  693.             else:
  694.                 raise TIMEOUT('Timeout exceeded in read_nonblocking().')
  695.         
  696.         if self.child_fd in r:
  697.             
  698.             try:
  699.                 s = os.read(self.child_fd, size)
  700.             except OSError:
  701.                 e = None
  702.                 self.flag_eof = True
  703.                 raise EOF('End Of File (EOF) in read_nonblocking(). Exception style platform.')
  704.  
  705.             if s == '':
  706.                 self.flag_eof = True
  707.                 raise EOF('End Of File (EOF) in read_nonblocking(). Empty string style platform.')
  708.             
  709.             if self.logfile is not None:
  710.                 self.logfile.write(s)
  711.                 self.logfile.flush()
  712.             
  713.             return s
  714.         
  715.         raise ExceptionPexpect('Reached an unexpected state in read_nonblocking().')
  716.  
  717.     
  718.     def read(self, size = -1):
  719.         '''This reads at most "size" bytes from the file 
  720.         (less if the read hits EOF before obtaining size bytes). 
  721.         If the size argument is negative or omitted, 
  722.         read all data until EOF is reached. 
  723.         The bytes are returned as a string object. 
  724.         An empty string is returned when EOF is encountered immediately.
  725.         '''
  726.         if size == 0:
  727.             return ''
  728.         
  729.         if size < 0:
  730.             self.expect(self.delimiter)
  731.             return self.before
  732.         
  733.         cre = re.compile('.{%d}' % size, re.DOTALL)
  734.         index = self.expect([
  735.             cre,
  736.             self.delimiter])
  737.         if index == 0:
  738.             return self.after
  739.         
  740.         return self.before
  741.  
  742.     
  743.     def readline(self, size = -1):
  744.         '''This reads and returns one entire line. A trailing newline is kept in
  745.         the string, but may be absent when a file ends with an incomplete line. 
  746.         Note: This readline() looks for a \\r\\n pair even on UNIX because
  747.         this is what the pseudo tty device returns. So contrary to what you
  748.         may expect you will receive the newline as \\r\\n.
  749.         An empty string is returned when EOF is hit immediately.
  750.         Currently, the size agument is mostly ignored, so this behavior is not
  751.         standard for a file-like object. If size is 0 then an empty string
  752.         is returned.
  753.         '''
  754.         if size == 0:
  755.             return ''
  756.         
  757.         index = self.expect([
  758.             '\r\n',
  759.             self.delimiter])
  760.         if index == 0:
  761.             return self.before + '\r\n'
  762.         else:
  763.             return self.before
  764.  
  765.     
  766.     def __iter__(self):
  767.         '''This is to support iterators over a file-like object.
  768.         '''
  769.         return self
  770.  
  771.     
  772.     def next(self):
  773.         '''This is to support iterators over a file-like object.
  774.         '''
  775.         result = self.readline()
  776.         if result == '':
  777.             raise StopIteration
  778.         
  779.         return result
  780.  
  781.     
  782.     def readlines(self, sizehint = -1):
  783.         '''This reads until EOF using readline() and returns a list containing 
  784.         the lines thus read. The optional "sizehint" argument is ignored.
  785.         '''
  786.         lines = []
  787.         while True:
  788.             line = self.readline()
  789.             if not line:
  790.                 break
  791.             
  792.             lines.append(line)
  793.         return lines
  794.  
  795.     
  796.     def write(self, str):
  797.         '''This is similar to send() except that there is no return value.
  798.         '''
  799.         self.send(str)
  800.  
  801.     
  802.     def writelines(self, sequence):
  803.         '''This calls write() for each element in the sequence.
  804.         The sequence can be any iterable object producing strings, 
  805.         typically a list of strings. This does not add line separators
  806.         There is no return value.
  807.         '''
  808.         for str in sequence:
  809.             self.write(str)
  810.         
  811.  
  812.     
  813.     def send(self, str):
  814.         '''This sends a string to the child process.
  815.         This returns the number of bytes written.
  816.         If a log file was set then the data is also written to the log.
  817.         '''
  818.         time.sleep(self.delaybeforesend)
  819.         if self.logfile is not None:
  820.             self.logfile.write(str)
  821.             self.logfile.flush()
  822.         
  823.         c = os.write(self.child_fd, str)
  824.         return c
  825.  
  826.     
  827.     def sendline(self, str = ''):
  828.         '''This is like send(), but it adds a line feed (os.linesep).
  829.         This returns the number of bytes written.
  830.         '''
  831.         n = self.send(str)
  832.         n = n + self.send(os.linesep)
  833.         return n
  834.  
  835.     
  836.     def sendeof(self):
  837.         '''This sends an EOF to the child.
  838.         This sends a character which causes the pending parent output
  839.         buffer to be sent to the waiting child program without
  840.         waiting for end-of-line. If it is the first character of the
  841.         line, the read() in the user program returns 0, which
  842.         signifies end-of-file. This means to work as expected 
  843.         a sendeof() has to be called at the begining of a line. 
  844.         This method does not send a newline. It is the responsibility
  845.         of the caller to ensure the eof is sent at the beginning of a line.
  846.         '''
  847.         fd = sys.stdin.fileno()
  848.         old = termios.tcgetattr(fd)
  849.         new = termios.tcgetattr(fd)
  850.         new[3] = new[3] | termios.ICANON
  851.         
  852.         try:
  853.             termios.tcsetattr(fd, termios.TCSADRAIN, new)
  854.             if 'CEOF' in dir(termios):
  855.                 os.write(self.child_fd, '%c' % termios.CEOF)
  856.             else:
  857.                 os.write(self.child_fd, '\x04')
  858.         finally:
  859.             termios.tcsetattr(fd, termios.TCSADRAIN, old)
  860.  
  861.  
  862.     
  863.     def eof(self):
  864.         '''This returns True if the EOF exception was ever raised.
  865.         '''
  866.         return self.flag_eof
  867.  
  868.     
  869.     def terminate(self, force = False):
  870.         '''This forces a child process to terminate.
  871.         It starts nicely with SIGHUP and SIGINT. If "force" is True then
  872.         moves onto SIGKILL.
  873.         This returns True if the child was terminated.
  874.         This returns False if the child could not be terminated.
  875.         '''
  876.         if not self.isalive():
  877.             return True
  878.         
  879.         self.kill(signal.SIGHUP)
  880.         time.sleep(self.delayafterterminate)
  881.         if not self.isalive():
  882.             return True
  883.         
  884.         self.kill(signal.SIGCONT)
  885.         time.sleep(self.delayafterterminate)
  886.         if not self.isalive():
  887.             return True
  888.         
  889.         self.kill(signal.SIGINT)
  890.         time.sleep(self.delayafterterminate)
  891.         if not self.isalive():
  892.             return True
  893.         
  894.         if force:
  895.             self.kill(signal.SIGKILL)
  896.             time.sleep(self.delayafterterminate)
  897.             if not self.isalive():
  898.                 return True
  899.             else:
  900.                 return False
  901.         
  902.         return False
  903.  
  904.     
  905.     def wait(self):
  906.         '''This waits until the child exits. This is a blocking call.
  907.             This will not read any data from the child, so this will block forever
  908.             if the child has unread output and has terminated. In other words, the child
  909.             may have printed output then called exit(); but, technically, the child is
  910.             still alive until its output is read.
  911.         '''
  912.         if self.isalive():
  913.             (pid, status) = os.waitpid(self.pid, 0)
  914.         else:
  915.             raise ExceptionPexpect('Cannot wait for dead child process.')
  916.         self.exitstatus = os.WEXITSTATUS(status)
  917.         if os.WIFEXITED(status):
  918.             self.status = status
  919.             self.exitstatus = os.WEXITSTATUS(status)
  920.             self.signalstatus = None
  921.             self.terminated = True
  922.         elif os.WIFSIGNALED(status):
  923.             self.status = status
  924.             self.exitstatus = None
  925.             self.signalstatus = os.WTERMSIG(status)
  926.             self.terminated = True
  927.         elif os.WIFSTOPPED(status):
  928.             raise ExceptionPexpect('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?')
  929.         
  930.         return self.exitstatus
  931.  
  932.     
  933.     def isalive(self):
  934.         '''This tests if the child process is running or not.
  935.         This is non-blocking. If the child was terminated then this
  936.         will read the exitstatus or signalstatus of the child.
  937.         This returns True if the child process appears to be running or False if not.
  938.         It can take literally SECONDS for Solaris to return the right status.
  939.         '''
  940.         if self.terminated:
  941.             return False
  942.         
  943.         if self.flag_eof:
  944.             waitpid_options = 0
  945.         else:
  946.             waitpid_options = os.WNOHANG
  947.         
  948.         try:
  949.             (pid, status) = os.waitpid(self.pid, waitpid_options)
  950.         except OSError:
  951.             e = None
  952.             if e[0] == errno.ECHILD:
  953.                 raise ExceptionPexpect('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?')
  954.             else:
  955.                 raise e
  956.         except:
  957.             e[0] == errno.ECHILD
  958.  
  959.         if pid == 0:
  960.             
  961.             try:
  962.                 (pid, status) = os.waitpid(self.pid, waitpid_options)
  963.             except OSError:
  964.                 e = None
  965.                 if e[0] == errno.ECHILD:
  966.                     raise ExceptionPexpect('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?')
  967.                 else:
  968.                     raise e
  969.             except:
  970.                 e[0] == errno.ECHILD
  971.  
  972.             if pid == 0:
  973.                 return True
  974.             
  975.         
  976.         if pid == 0:
  977.             return True
  978.         
  979.         if os.WIFEXITED(status):
  980.             self.status = status
  981.             self.exitstatus = os.WEXITSTATUS(status)
  982.             self.signalstatus = None
  983.             self.terminated = True
  984.         elif os.WIFSIGNALED(status):
  985.             self.status = status
  986.             self.exitstatus = None
  987.             self.signalstatus = os.WTERMSIG(status)
  988.             self.terminated = True
  989.         elif os.WIFSTOPPED(status):
  990.             raise ExceptionPexpect('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?')
  991.         
  992.         return False
  993.  
  994.     
  995.     def kill(self, sig):
  996.         '''This sends the given signal to the child application.
  997.         In keeping with UNIX tradition it has a misleading name.
  998.         It does not necessarily kill the child unless
  999.         you send the right signal.
  1000.         '''
  1001.         if self.isalive():
  1002.             os.kill(self.pid, sig)
  1003.         
  1004.  
  1005.     
  1006.     def compile_pattern_list(self, patterns):
  1007.         '''This compiles a pattern-string or a list of pattern-strings.
  1008.         Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or 
  1009.         a list of those. Patterns may also be None which results in
  1010.         an empty list.
  1011.  
  1012.         This is used by expect() when calling expect_list().
  1013.         Thus expect() is nothing more than::
  1014.              cpl = self.compile_pattern_list(pl)
  1015.              return self.expect_list(clp, timeout)
  1016.  
  1017.         If you are using expect() within a loop it may be more
  1018.         efficient to compile the patterns first and then call expect_list().
  1019.         This avoid calls in a loop to compile_pattern_list():
  1020.              cpl = self.compile_pattern_list(my_pattern)
  1021.              while some_condition:
  1022.                 ...
  1023.                 i = self.expect_list(clp, timeout)
  1024.                 ...
  1025.         '''
  1026.         if patterns is None:
  1027.             return []
  1028.         
  1029.         if type(patterns) is not types.ListType:
  1030.             patterns = [
  1031.                 patterns]
  1032.         
  1033.         compile_flags = re.DOTALL
  1034.         if self.ignorecase:
  1035.             compile_flags = compile_flags | re.IGNORECASE
  1036.         
  1037.         compiled_pattern_list = []
  1038.         for p in patterns:
  1039.             if type(p) is types.StringType:
  1040.                 compiled_pattern_list.append(re.compile(p, compile_flags))
  1041.                 continue
  1042.             if p is EOF:
  1043.                 compiled_pattern_list.append(EOF)
  1044.                 continue
  1045.             if p is TIMEOUT:
  1046.                 compiled_pattern_list.append(TIMEOUT)
  1047.                 continue
  1048.             if type(p) is type(re.compile('')):
  1049.                 compiled_pattern_list.append(p)
  1050.                 continue
  1051.             raise TypeError('Argument must be one of StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p)))
  1052.         
  1053.         return compiled_pattern_list
  1054.  
  1055.     
  1056.     def expect(self, pattern, timeout = -1, searchwindowsize = None):
  1057.         """This seeks through the stream until a pattern is matched.
  1058.         The pattern is overloaded and may take several types including a list.
  1059.         The pattern can be a StringType, EOF, a compiled re, or a list of
  1060.         those types. Strings will be compiled to re types. This returns the
  1061.         index into the pattern list. If the pattern was not a list this
  1062.         returns index 0 on a successful match. This may raise exceptions for
  1063.         EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add
  1064.         EOF or TIMEOUT to the pattern list.
  1065.  
  1066.         After a match is found the instance attributes
  1067.         'before', 'after' and 'match' will be set.
  1068.         You can see all the data read before the match in 'before'.
  1069.         You can see the data that was matched in 'after'.
  1070.         The re.MatchObject used in the re match will be in 'match'.
  1071.         If an error occured then 'before' will be set to all the
  1072.         data read so far and 'after' and 'match' will be None.
  1073.  
  1074.         If timeout is -1 then timeout will be set to the self.timeout value.
  1075.  
  1076.         Note: A list entry may be EOF or TIMEOUT instead of a string.
  1077.         This will catch these exceptions and return the index
  1078.         of the list entry instead of raising the exception.
  1079.         The attribute 'after' will be set to the exception type.
  1080.         The attribute 'match' will be None.
  1081.         This allows you to write code like this:
  1082.                 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
  1083.                 if index == 0:
  1084.                     do_something()
  1085.                 elif index == 1:
  1086.                     do_something_else()
  1087.                 elif index == 2:
  1088.                     do_some_other_thing()
  1089.                 elif index == 3:
  1090.                     do_something_completely_different()
  1091.         instead of code like this:
  1092.                 try:
  1093.                     index = p.expect (['good', 'bad'])
  1094.                     if index == 0:
  1095.                         do_something()
  1096.                     elif index == 1:
  1097.                         do_something_else()
  1098.                 except EOF:
  1099.                     do_some_other_thing()
  1100.                 except TIMEOUT:
  1101.                     do_something_completely_different()
  1102.         These two forms are equivalent. It all depends on what you want.
  1103.         You can also just expect the EOF if you are waiting for all output
  1104.         of a child to finish. For example:
  1105.                 p = pexpect.spawn('/bin/ls')
  1106.                 p.expect (pexpect.EOF)
  1107.                 print p.before
  1108.  
  1109.         If you are trying to optimize for speed then see expect_list().
  1110.         """
  1111.         compiled_pattern_list = self.compile_pattern_list(pattern)
  1112.         return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
  1113.  
  1114.     
  1115.     def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1):
  1116.         '''This takes a list of compiled regular expressions and returns 
  1117.         the index into the pattern_list that matched the child output.
  1118.         The list may also contain EOF or TIMEOUT (which are not
  1119.         compiled regular expressions). This method is similar to
  1120.         the expect() method except that expect_list() does not
  1121.         recompile the pattern list on every call.
  1122.         This may help if you are trying to optimize for speed, otherwise
  1123.         just use the expect() method.  This is called by expect().
  1124.         If timeout==-1 then the self.timeout value is used.
  1125.         If searchwindowsize==-1 then the self.searchwindowsize value is used.
  1126.         '''
  1127.         self.patterns = pattern_list
  1128.         if timeout == -1:
  1129.             timeout = self.timeout
  1130.         
  1131.         if timeout is not None:
  1132.             end_time = time.time() + timeout
  1133.         
  1134.         if searchwindowsize == -1:
  1135.             searchwindowsize = self.searchwindowsize
  1136.         
  1137.         
  1138.         try:
  1139.             incoming = self.buffer
  1140.             while True:
  1141.                 first_match = -1
  1142.                 for cre in pattern_list:
  1143.                     if cre is EOF or cre is TIMEOUT:
  1144.                         continue
  1145.                     
  1146.                     if searchwindowsize is None:
  1147.                         match = cre.search(incoming)
  1148.                     else:
  1149.                         startpos = max(0, len(incoming) - searchwindowsize)
  1150.                         match = cre.search(incoming, startpos)
  1151.                     if match is None:
  1152.                         continue
  1153.                     
  1154.                     if first_match > match.start() or first_match == -1:
  1155.                         first_match = match.start()
  1156.                         self.match = match
  1157.                         self.match_index = pattern_list.index(cre)
  1158.                         continue
  1159.                 
  1160.                 if first_match > -1:
  1161.                     self.buffer = incoming[self.match.end():]
  1162.                     self.before = incoming[:self.match.start()]
  1163.                     self.after = incoming[self.match.start():self.match.end()]
  1164.                     return self.match_index
  1165.                 
  1166.                 if timeout < 0 and timeout is not None:
  1167.                     raise TIMEOUT('Timeout exceeded in expect_list().')
  1168.                 
  1169.                 c = self.read_nonblocking(self.maxread, timeout)
  1170.                 time.sleep(0.0001)
  1171.                 incoming = incoming + c
  1172.                 if timeout is not None:
  1173.                     timeout = end_time - time.time()
  1174.                     continue
  1175.         except EOF:
  1176.             e = None
  1177.             self.buffer = ''
  1178.             self.before = incoming
  1179.             self.after = EOF
  1180.             if EOF in pattern_list:
  1181.                 self.match = EOF
  1182.                 self.match_index = pattern_list.index(EOF)
  1183.                 return self.match_index
  1184.             else:
  1185.                 self.match = None
  1186.                 self.match_index = None
  1187.                 raise EOF(str(e) + '\n' + str(self))
  1188.         except TIMEOUT:
  1189.             e = None
  1190.             self.before = incoming
  1191.             self.after = TIMEOUT
  1192.             if TIMEOUT in pattern_list:
  1193.                 self.match = TIMEOUT
  1194.                 self.match_index = pattern_list.index(TIMEOUT)
  1195.                 return self.match_index
  1196.             else:
  1197.                 self.match = None
  1198.                 self.match_index = None
  1199.                 raise TIMEOUT(str(e) + '\n' + str(self))
  1200.         except Exception:
  1201.             self.before = incoming
  1202.             self.after = None
  1203.             self.match = None
  1204.             self.match_index = None
  1205.             raise 
  1206.  
  1207.  
  1208.     
  1209.     def getwinsize(self):
  1210.         '''This returns the terminal window size of the child tty.
  1211.         The return value is a tuple of (rows, cols).
  1212.         '''
  1213.         if 'TIOCGWINSZ' in dir(termios):
  1214.             TIOCGWINSZ = termios.TIOCGWINSZ
  1215.         else:
  1216.             TIOCGWINSZ = 0x40087468L
  1217.         s = struct.pack('HHHH', 0, 0, 0, 0)
  1218.         x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
  1219.         return struct.unpack('HHHH', x)[0:2]
  1220.  
  1221.     
  1222.     def setwinsize(self, r, c):
  1223.         '''This sets the terminal window size of the child tty.
  1224.         This will cause a SIGWINCH signal to be sent to the child.
  1225.         This does not change the physical window size.
  1226.         It changes the size reported to TTY-aware applications like
  1227.         vi or curses -- applications that respond to the SIGWINCH signal.
  1228.         '''
  1229.         if 'TIOCSWINSZ' in dir(termios):
  1230.             TIOCSWINSZ = termios.TIOCSWINSZ
  1231.         else:
  1232.             TIOCSWINSZ = -2146929561
  1233.         if TIOCSWINSZ == 0x80087467L:
  1234.             TIOCSWINSZ = -2146929561
  1235.         
  1236.         s = struct.pack('HHHH', r, c, 0, 0)
  1237.         fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
  1238.  
  1239.     
  1240.     def interact(self, escape_character = chr(29), input_filter = None, output_filter = None):
  1241.         '''This gives control of the child process to the interactive user
  1242.         (the human at the keyboard).
  1243.         Keystrokes are sent to the child process, and the stdout and stderr
  1244.         output of the child process is printed.
  1245.         This simply echos the child stdout and child stderr to the real
  1246.         stdout and it echos the real stdin to the child stdin.
  1247.         When the user types the escape_character this method will stop.
  1248.         The default for escape_character is ^]. This should not be confused
  1249.         with ASCII 27 -- the ESC character. ASCII 29 was chosen
  1250.         for historical merit because this is the character used
  1251.         by \'telnet\' as the escape character. The escape_character will
  1252.         not be sent to the child process.
  1253.  
  1254.         You may pass in optional input and output filter functions.
  1255.         These functions should take a string and return a string.
  1256.         The output_filter will be passed all the output from the child process.
  1257.         The input_filter will be passed all the keyboard input from the user.
  1258.         The input_filter is run BEFORE the check for the escape_character.
  1259.  
  1260.         Note that if you change the window size of the parent
  1261.         the SIGWINCH signal will not be passed through to the child.
  1262.         If you want the child window size to change when the parent\'s
  1263.         window size changes then do something like the following example:
  1264.             import pexpect, struct, fcntl, termios, signal, sys
  1265.             def sigwinch_passthrough (sig, data):
  1266.                 s = struct.pack("HHHH", 0, 0, 0, 0)
  1267.                 a = struct.unpack(\'hhhh\', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s))
  1268.                 global p
  1269.                 p.setwinsize(a[0],a[1])
  1270.             p = pexpect.spawn(\'/bin/bash\') # Note this is global and used in sigwinch_passthrough.
  1271.             signal.signal(signal.SIGWINCH, sigwinch_passthrough)
  1272.             p.interact()
  1273.         '''
  1274.         self.stdout.write(self.buffer)
  1275.         self.stdout.flush()
  1276.         self.buffer = ''
  1277.         mode = tty.tcgetattr(self.STDIN_FILENO)
  1278.         tty.setraw(self.STDIN_FILENO)
  1279.         
  1280.         try:
  1281.             self._spawn__interact_copy(escape_character, input_filter, output_filter)
  1282.         finally:
  1283.             tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
  1284.  
  1285.  
  1286.     
  1287.     def __interact_writen(self, fd, data):
  1288.         '''This is used by the interact() method.
  1289.         '''
  1290.         while data != '' and self.isalive():
  1291.             n = os.write(fd, data)
  1292.             data = data[n:]
  1293.  
  1294.     
  1295.     def __interact_read(self, fd):
  1296.         '''This is used by the interact() method.
  1297.         '''
  1298.         return os.read(fd, 1000)
  1299.  
  1300.     
  1301.     def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
  1302.         '''This is used by the interact() method.
  1303.         '''
  1304.         while self.isalive():
  1305.             (r, w, e) = self._spawn__select([
  1306.                 self.child_fd,
  1307.                 self.STDIN_FILENO], [], [])
  1308.             if self.child_fd in r:
  1309.                 data = self._spawn__interact_read(self.child_fd)
  1310.                 if output_filter:
  1311.                     data = output_filter(data)
  1312.                 
  1313.                 if self.logfile is not None:
  1314.                     self.logfile.write(data)
  1315.                     self.logfile.flush()
  1316.                 
  1317.                 os.write(self.STDOUT_FILENO, data)
  1318.             
  1319.             if self.STDIN_FILENO in r:
  1320.                 data = self._spawn__interact_read(self.STDIN_FILENO)
  1321.                 if input_filter:
  1322.                     data = input_filter(data)
  1323.                 
  1324.                 i = data.rfind(escape_character)
  1325.                 if i != -1:
  1326.                     data = data[:i]
  1327.                     self._spawn__interact_writen(self.child_fd, data)
  1328.                     break
  1329.                 
  1330.                 self._spawn__interact_writen(self.child_fd, data)
  1331.                 continue
  1332.  
  1333.     
  1334.     def __select(self, iwtd, owtd, ewtd, timeout = None):
  1335.         '''This is a wrapper around select.select() that ignores signals.
  1336.         If select.select raises a select.error exception and errno is an EINTR error then
  1337.         it is ignored. Mainly this is used to ignore sigwinch (terminal resize).
  1338.         '''
  1339.         if timeout is not None:
  1340.             end_time = time.time() + timeout
  1341.         
  1342.         while True:
  1343.             
  1344.             try:
  1345.                 return select.select(iwtd, owtd, ewtd, timeout)
  1346.             continue
  1347.             except select.error:
  1348.                 e = None
  1349.                 if e[0] == errno.EINTR:
  1350.                     if timeout is not None:
  1351.                         timeout = end_time - time.time()
  1352.                         if timeout < 0:
  1353.                             return ([], [], [])
  1354.                         
  1355.                     
  1356.                 else:
  1357.                     raise 
  1358.                 e[0] == errno.EINTR
  1359.             
  1360.  
  1361.             None<EXCEPTION MATCH>select.error
  1362.  
  1363.     
  1364.     def setmaxread(self, maxread):
  1365.         """This method is no longer supported or allowed.
  1366.         I don't like getters and setters without a good reason.
  1367.         """
  1368.         raise ExceptionPexpect('This method is no longer supported or allowed. Just assign a value to the maxread member variable.')
  1369.  
  1370.     
  1371.     def expect_exact(self, pattern_list, timeout = -1):
  1372.         '''This method is no longer supported or allowed.
  1373.         It was too hard to maintain and keep it up to date with expect_list.
  1374.         Few people used this method. Most people favored reliability over speed.
  1375.         The implementation is left in comments in case anyone needs to hack this
  1376.         feature back into their copy.
  1377.         If someone wants to diff this with expect_list and make them work
  1378.         nearly the same then I will consider adding this make in.
  1379.         '''
  1380.         raise ExceptionPexpect('This method is no longer supported or allowed.')
  1381.  
  1382.     
  1383.     def setlog(self, fileobject):
  1384.         '''This method is no longer supported or allowed.
  1385.         '''
  1386.         raise ExceptionPexpect('This method is no longer supported or allowed. Just assign a value to the logfile member variable.')
  1387.  
  1388.  
  1389.  
  1390. def which(filename):
  1391.     '''This takes a given filename; tries to find it in the environment path; 
  1392.     then checks if it is executable.
  1393.     This returns the full path to the filename if found and executable.
  1394.     Otherwise this returns None.
  1395.     '''
  1396.     if os.path.dirname(filename) != '':
  1397.         if os.access(filename, os.X_OK):
  1398.             return filename
  1399.         
  1400.     
  1401.     if not os.environ.has_key('PATH') or os.environ['PATH'] == '':
  1402.         p = os.defpath
  1403.     else:
  1404.         p = os.environ['PATH']
  1405.     pathlist = string.split(p, os.pathsep)
  1406.     for path in pathlist:
  1407.         f = os.path.join(path, filename)
  1408.         if os.access(f, os.X_OK):
  1409.             return f
  1410.             continue
  1411.     
  1412.  
  1413.  
  1414. def split_command_line(command_line):
  1415.     """This splits a command line into a list of arguments.
  1416.     It splits arguments on spaces, but handles
  1417.     embedded quotes, doublequotes, and escaped characters.
  1418.     It's impossible to do this with a regular expression, so
  1419.     I wrote a little state machine to parse the command line.
  1420.     """
  1421.     arg_list = []
  1422.     arg = ''
  1423.     state_basic = 0
  1424.     state_esc = 1
  1425.     state_singlequote = 2
  1426.     state_doublequote = 3
  1427.     state_whitespace = 4
  1428.     state = state_basic
  1429.     for c in command_line:
  1430.         if state == state_basic or state == state_whitespace:
  1431.             if c == '\\':
  1432.                 state = state_esc
  1433.             elif c == "'":
  1434.                 state = state_singlequote
  1435.             elif c == '"':
  1436.                 state = state_doublequote
  1437.             elif c.isspace():
  1438.                 if state == state_whitespace:
  1439.                     pass
  1440.                 else:
  1441.                     arg_list.append(arg)
  1442.                     arg = ''
  1443.                     state = state_whitespace
  1444.             else:
  1445.                 arg = arg + c
  1446.                 state = state_basic
  1447.         c == '\\'
  1448.         if state == state_esc:
  1449.             arg = arg + c
  1450.             state = state_basic
  1451.             continue
  1452.         if state == state_singlequote:
  1453.             if c == "'":
  1454.                 state = state_basic
  1455.             else:
  1456.                 arg = arg + c
  1457.         c == "'"
  1458.         if state == state_doublequote:
  1459.             if c == '"':
  1460.                 state = state_basic
  1461.             else:
  1462.                 arg = arg + c
  1463.         c == '"'
  1464.     
  1465.     if arg != '':
  1466.         arg_list.append(arg)
  1467.     
  1468.     return arg_list
  1469.  
  1470.