Path: blob/master/Tools/autotest/pysim/fdpexpect.py
9743 views
# flake8: noqa12"""This is like pexpect, but will work on any file descriptor that you pass it.3So you are responsible for opening and close the file descriptor.45$Id: fdpexpect.py 505 2007-12-26 21:33:50Z noah $6"""78import os910from pexpect import ExceptionPexpect, spawn1112__all__ = ['fdspawn']131415class fdspawn(spawn):16"""This is like pexpect.spawn but allows you to supply your own open file17descriptor. For example, you could use it to read through a file looking18for patterns, or to control a modem or serial device. """1920def __init__(self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None):2122"""This takes a file descriptor (an int) or an object that support the23fileno() method (returning an int). All Python file-like objects24support fileno(). """2526# TODO: Add better handling of trying to use fdspawn in place of spawn27# TODO: (overload to allow fdspawn to also handle commands as spawn does.2829if not isinstance(fd, int) and hasattr(fd, 'fileno'):30fd = fd.fileno()3132if not isinstance(fd, int):33raise ExceptionPexpect(34"The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.")3536try: # make sure fd is a valid file descriptor37os.fstat(fd)38except OSError:39raise ExceptionPexpect("The fd argument is not a valid file descriptor.")4041self.args = None42self.command = None43spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile)44self.child_fd = fd45self.own_fd = False46self.closed = False47self.name = '<file descriptor %d>' % fd4849def __del__(self):5051return5253def close(self):5455if self.child_fd == -1:56return57if self.own_fd:58self.close(self)59else:60self.flush()61os.close(self.child_fd)62self.child_fd = -163self.closed = True6465def isalive(self):6667"""This checks if the file descriptor is still valid. If os.fstat()68does not raise an exception then we assume it is alive. """6970if self.child_fd == -1:71return False72try:73os.fstat(self.child_fd)74return True75except:76return False7778def terminate(self, force=False):7980raise ExceptionPexpect('This method is not valid for file descriptors.')8182def kill(self, sig):8384return858687