1 """This is like pexpect, but will work on any file descriptor that you pass it.
2 So you are reponsible for opening and close the file descriptor.
4 $Id: fdpexpect.py 505 2007-12-26 21:33:50Z noah $
12 class fdspawn (spawn):
14 """This is like pexpect.spawn but allows you to supply your own open file
15 descriptor. For example, you could use it to read through a file looking
16 for patterns, or to control a modem or serial device. """
18 def __init__ (self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None):
20 """This takes a file descriptor (an int) or an object that support the
21 fileno() method (returning an int). All Python file-like objects
24 ### TODO: Add better handling of trying to use fdspawn in place of spawn
25 ### TODO: (overload to allow fdspawn to also handle commands as spawn does.
27 if type(fd) != type(0) and hasattr(fd, 'fileno'):
30 if type(fd) != type(0):
31 raise ExceptionPexpect ('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')
33 try: # make sure fd is a valid file descriptor
36 raise ExceptionPexpect, 'The fd argument is not a valid file descriptor.'
40 spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile)
44 self.name = '<file descriptor %d>' % fd
52 if self.child_fd == -1:
58 os.close(self.child_fd)
64 """This checks if the file descriptor is still valid. If os.fstat()
65 does not raise an exception then we assume it is alive. """
67 if self.child_fd == -1:
70 os.fstat(self.child_fd)
75 def terminate (self, force=False):
77 raise ExceptionPexpect ('This method is not valid for file descriptors.')