pexpect (version 0.98)
index
/home/noah/pexpect/pexpect.py

Pexpect is a Python module for spawning child applications;
controlling them; and responding to expected patterns in their output.
Pexpect can be used for automating interactive applications such as
ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts
for duplicating software package installations on different servers.
It can be used for automated software testing. Pexpect is in the spirit of
Don Libes' Expect, but Pexpect is pure Python. Other Expect-like
modules for Python require TCL and Expect or require C extensions to
be compiled. Pexpect does not use C, Expect, or TCL extensions. It
should work on any platform that supports the standard Python pty
module. The Pexpect interface focuses on ease of use so that simple
tasks are easy.
 
Pexpect is Open Source, Free, and all Good that stuff.
License: Python Software Foundation License
         http://www.opensource.org/licenses/PythonSoftFoundation.html
 
Noah Spurrier
 
$Revision: 1.80 $
$Date: 2003/05/17 06:32:00 $

 
Modules
            
fcntl
os
pty
re
resource
select
string
struct
sys
termios
tty
 
Classes
            
exceptions.Exception
ExceptionPexpect
EOF
TIMEOUT
spawn
 
class EOF(ExceptionPexpect)
      Raised when EOF is read from a child.
 
  
Method resolution order:
EOF
ExceptionPexpect
exceptions.Exception

Data and non-method functions defined here:
__doc__ = 'Raised when EOF is read from a child.'
__module__ = 'pexpect'

Methods inherited from ExceptionPexpect:
__init__(self, value)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)
 
class ExceptionPexpect(exceptions.Exception)
      Base class for all exceptions raised by this module.
 
   Methods defined here:
__init__(self, value)
__str__(self)

Data and non-method functions defined here:
__doc__ = 'Base class for all exceptions raised by this module.'
__module__ = 'pexpect'

Methods inherited from exceptions.Exception:
__getitem__(...)
 
class TIMEOUT(ExceptionPexpect)
      Raised when a read time exceeds the timeout.
 
  
Method resolution order:
TIMEOUT
ExceptionPexpect
exceptions.Exception

Data and non-method functions defined here:
__doc__ = 'Raised when a read time exceeds the timeout.'
__module__ = 'pexpect'

Methods inherited from ExceptionPexpect:
__init__(self, value)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)
 
class spawn
      This is the main class interface for Pexpect. Use this class to
start and control child applications.
 
   Methods defined here:
__del__(self)
This makes sure that no system resources are left open.
Python only garbage collects Python objects. OS file descriptors
are not Python objects, so they must be handled explicitly.
If the child file descriptor was opened outside of this class
(passed to the constructor) then this does not close it.
__init__(self, command, args=[], timeout=30)
This is the constructor. The command parameter may be a string
that includes a command and any arguments to the command. For example:
    p = pexpect.spawn ('/usr/bin/ftp')
    p = pexpect.spawn ('/usr/bin/ssh user@example.com')
    p = pexpect.spawn ('ls -latr /tmp')
You may also construct it with a list of arguments like so:
    p = pexpect.spawn ('/usr/bin/ftp', [])
    p = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
    p = pexpect.spawn ('ls', ['-latr', '/tmp'])
After this the child application will be created and
will be ready to talk to. For normal use, see expect() and 
send() and sendline().
 
If the command parameter is an integer AND a valid file descriptor
then spawn will talk to the file descriptor instead. This can be
used to act expect features to any file descriptor. For example:
    fd = os.open ('somefile.txt', os.O_RDONLY)
    s = pexpect.spawn (fd)
The original creator of the file descriptor is responsible
for closing it. Spawn will not try to close it and spawn will
raise an exception if you try to call spawn.close().
__iter__(self)
This is to support interators over a file-like object.
_spawn__interact_copy = __interact_copy(self, escape_character=None)
This is used by the interact() method.
_spawn__interact_read = __interact_read(self, fd)
This is used by the interact() method.
_spawn__interact_writen = __interact_writen(self, fd, data)
This is used by the interact() method.
_spawn__spawn = __spawn(self)
This starts the given command in a child process. This does
all the fork/exec type of stuff for a pty. This is called by
__init__. The args parameter is a list, command is a string.
close(self, wait=1)
This closes the connection with the child application.
It makes no attempt to actually kill the child or wait for its status.
If the file descriptor was set by passing a file descriptor
to the constructor then this method raises an exception.
Note that calling close() more than once is valid.
This emulates standard Python behavior with files.
If wait is set to True then close will wait
for the exit status of the process. This is a blocking call,
but this usually takes almost no time at all. If you are
creating lots of children then you usually want to call wait.
Only set wait to false if yo uknow the child will
continue to run after closing the controlling TTY.
compile_pattern_list(self, patterns)
This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOFTIMEOUT, SRE_Pattern, or 
a list of those.
 
This is used by expect() when calling expect_list().
Thus expect() is nothing more than::
     cpl = compile_pattern_list(pl)
     return expect_list(clp, timeout)
 
If you are using expect() within a loop it may be more
efficient to compile the patterns first and then call expect_list().
This avoid calls in a loop to compile_pattern_list():
     cpl = compile_pattern_list(my_pattern)
     while some_condition:
        ...
        i = expect_list(clp, timeout)
        ...
eof(self)
This returns 1 if the EOF exception was raised.
expect(self, pattern, timeout=-1)
This seeks through the stream until a pattern is matched.
The pattern is overloaded and may take several types including a list.
The pattern can be a StringType, EOF, a compiled re, or
a list of those types. Strings will be compiled to re types.
This returns the index into the pattern list. If the pattern was
not a list this returns index 0 on a successful match.
This may raise exceptions for EOF or TIMEOUT.
To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to
the pattern list.
 
After a match is found the instance attributes
'before', 'after' and 'match' will be set.
You can see all the data read before the match in 'before'.
You can see the data that was matched in 'after'.
The re.MatchObject used in the re match will be in 'match'.
If an error occured then 'before' will be set to all the
data read so far and 'after' and 'match' will be None.
 
If timeout is -1 then timeout will be set to the self.timeout value.
 
Note: A list entry may be EOF or TIMEOUT instead of a string.
This will catch these exceptions and return the index
of the list entry instead of raising the exception.
The attribute 'after' will be set to the exception type.
The attribute 'match' will be None.
This allows you to write code like this:
        index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
        if index == 0:
            do_something()
        elif index == 1:
            do_something_else()
        elif index == 2:
            do_some_other_thing()
        elif index == 3:
            do_something_completely_different()
instead of code like this:
        try:
            index = p.expect (['good', 'bad'])
            if index == 0:
                do_something()
            elif index == 1:
                do_something_else()
        except EOF:
            do_some_other_thing()
        except TIMEOUT:
            do_something_completely_different()
These two forms are equivalent. It all depends on what you want.
You can also just expect the EOF if you are waiting for all output
of a child to finish. For example:
        p = pexpect.spawn('/bin/ls')
        p.expect (pexpect.EOF)
        print p.before
expect_exact(self, pattern_list, timeout=-1)
This is similar to expect() except that it takes
list of plain strings instead of regular expressions.
The idea is that this should be much faster. It could also be
useful when you don't want to have to worry about escaping
regular expression characters that you want to match.
You may also pass just a string without a list and the single
string will be converted to a list.
If timeout is -1 then timeout will be set to the self.timeout value.
expect_list(self, pattern_list, timeout=-1)
This takes a list of compiled regular expressions and returns 
the index into the pattern_list that matched the child's output.
This is called by expect(). It is similar to the expect() method
except that expect_list() is not overloaded. You must not pass
anything except a list of compiled regular expressions.
If timeout is -1 then timeout will be set to the self.timeout value.
fileno(self)
This returns the file descriptor of the pty for the child.
flush(self)
This does nothing.
getwinsize(self)
This returns the window size of the child tty.
The return value is a tuple of (rows, cols).
interact(self, escape_character='\x1d')
This gives control of the child process to the interactive user
(the human at the keyboard).
Keystrokes are sent to the child process, and the stdout and stderr
output of the child process is printed.
When the user types the escape_character this method will stop.
The default for escape_character is ^] (ASCII 29).
This simply echos the child stdout and child stderr to the real
stdout and it echos the real stdin to the child stdin.
isalive(self)
This tests if the child process is running or not.
This returns 1 if the child process appears to be running or 0 if not.
This also sets the exitstatus attribute.
It can take literally SECONDS for Solaris to return the right status.
This is the most wiggly part of Pexpect, but I think I've almost got
it nailed down.
isatty(self)
This returns 1 if the file descriptor is open and
connected to a tty(-like) device, else 0.
kill(self, sig)
This sends the given signal to the child application.
In keeping with UNIX tradition it has a misleading name.
It does not necessarily kill the child unless
you send the right signal.
next(self)
This is to support iterators over a file-like object.
read(self, size=-1)
This reads at most size bytes from the file 
(less if the read hits EOF before obtaining size bytes). 
If the size argument is negative or omitted, 
read all data until EOF is reached. 
The bytes are returned as a string object. 
An empty string is returned when EOF is encountered immediately.
read_nonblocking(self, size=-1, timeout=None)
This reads at most size characters from the child application.
It includes a timeout. If the read does not complete within the
timeout period then a TIMEOUT exception is raised.
If the end of file is read then an EOF exception will be raised.
If a log file was set using setlog() then all data will
also be written to the log file.
 
Notice that if this method is called with timeout=None 
then it actually may block.
 
This is a non-blocking wrapper around os.read().
It uses select.select() to supply a timeout.
readline(self, size=-1)
This reads and returns one entire line. A trailing newline is kept in
        the string, but may be absent when a file ends with an incomplete line. 
        Note: This readline() looks for a 
 pair even on UNIX because this is 
        what the pseudo tty device returns. So contrary to what you may be used to
        you will get a newline as 
.
        An empty string is returned when EOF is hit immediately.
        Currently, the size agument is mostly ignored, so this behavior is not
        standard for a file-like object.
readlines(self, sizehint=-1)
This reads until EOF using readline() and returns a list containing 
the lines thus read. The optional sizehint argument is ignored.
send(self, str)
This sends a string to the child process.
This returns the number of bytes written.
sendeof(self)
This sends an EOF to the child.
This sends a character which causes the pending
child buffer to be sent to the waiting child program without
waiting for end-of-line. If it is the first character of the
line, the read() in the user program returns 0, which
signifies end-of-file. This means to make this work as expected 
sendeof() has to be called at the begining of a line. 
This method does not  send a newline. It is the responsibility
of the caller to ensure the eof is sent at the beginning of a line.
sendline(self, str='')
This is like send(), but it adds a line feed (os.linesep).
This returns the number of bytes written.
setecho(self, on)
This sets the terminal echo mode on or off.
setlog(self, fileobject)
This sets logging output to go to the given fileobject.
Set fileobject to None to stop logging.
setwinsize(self, r, c)
This sets the windowsize of the child tty.
This will cause a SIGWINCH signal to be sent to the child.
This does not change the physical window size.
It changes the size reported to TTY-aware applications like
vi or curses -- applications that respond to the SIGWINCH signal.
write(self, str)
This is similar to send() except that there is no return value.
writelines(self, sequence)
This calls write() for each element in the sequence.
The sequence can be any iterable object producing strings, 
typically a list of strings. This does not add line separators
There is no return value.

Data and non-method functions defined here:
__doc__ = 'This is the main class interface for Pexpect. Us...to\n start and control child applications.\n '
__module__ = 'pexpect'
 
Functions
            
_split_command_line(command_line)
This splits a command line into a list of arguments.
It splits arguments on spaces, but handles
embedded quotes, doublequotes, and escaped characters.
It's impossible to do this with a regular expression, so
I wrote a little state machine to parse the command line.
_which(filename)
This takes a given filename; tries to find it in the
environment path; then checks if it is executable.
run(command, args=[], timeout=30)
This runs a command; waits for it to finish; then returns
all output as a string. This is a utility interface around
the spawn class.
 
Data
             StringTypes = (<type 'str'>, <type 'unicode'>)
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', '__version__', '__revision__']
__file__ = './pexpect.py'
__name__ = 'pexpect'
__revision__ = '$Revision: 1.80 $'
__version__ = '0.98'