File: fdpexpect.py

package info (click to toggle)
pexpect 2.1-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 584 kB
  • ctags: 701
  • sloc: python: 3,036; makefile: 46
file content (73 lines) | stat: -rw-r--r-- 2,448 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
TODO: This is BETA. When it gets stable I will move it into the pexpect.py file.
"""

from pexpect import *
import os

__all__ = ['fdspawn']

class fdspawn (spawn):
    """This is like pexpect.spawn but allows you to supply your own,
    already open file descriptor. For example, you could use it to
    read through a file looking for patterns, or to control a modem or
    serial device.
    """
    def __init__ (self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None):
        """This takes a file descriptor (an int) or an object that support the fileno() method
            (returning an int). All Python file-like objects support fileno().
        """
        ### TODO: Add better handling of trying to use fdspawn in place of spawn
        ### TODO: (overload to allow fdspawn to also handle commands as spawn does.

        if type(fd) != type(0) and hasattr(fd, 'fileno'):
            fd = fd.fileno()

        if type(fd) != type(0):
            raise ExceptionPexpect ('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')

        try: # make sure fd is a valid file descriptor
            os.fstat(fd)
        except OSError:
            raise ExceptionPexpect, 'The fd argument is not a valid file descriptor.'

        self.args = None
        self.command = None
        spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile)
        self.child_fd = fd
        self.own_fd = False
        self.closed = False
        self.name = '<file descriptor %d>' % fd

    def __del__ (self):
        return

    def close (self):
        if super(fdspawn, self).child_fd == -1:
            return
        if self.own_fd:
            super(fdspawn, self).close (self)
        else:
            self.flush()
            os.close(super(fdspawn, self).child_fd)
            self.child_fd = -1
            self.closed = True

    def isalive (self):
        """This checks if the file descriptor is still valid.
            If os.fstat() does not raise an exception then we assume it is alive.
        """
        if self.child_fd == -1:
            return False
        try:
            os.fstat(self.child_fd)
            return True
        except:
            return False

    def terminate (self, force=False):
        raise ExceptionPexpect ('This method is not valid for file descriptors.')

    def kill (self, sig):
        return