fdpexpect.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. '''This is like pexpect, but it will work with any file descriptor that you
  2. pass it. You are reponsible for opening and close the file descriptor.
  3. This allows you to use Pexpect with sockets and named pipes (FIFOs).
  4. PEXPECT LICENSE
  5. This license is approved by the OSI and FSF as GPL-compatible.
  6. http://opensource.org/licenses/isc-license.txt
  7. Copyright (c) 2012, Noah Spurrier <noah@noah.org>
  8. PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
  9. PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
  10. COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  12. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  13. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  14. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  15. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  16. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  17. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  18. '''
  19. from .spawnbase import SpawnBase
  20. from .exceptions import ExceptionPexpect, TIMEOUT
  21. from .utils import select_ignore_interrupts
  22. import os
  23. __all__ = ['fdspawn']
  24. class fdspawn(SpawnBase):
  25. '''This is like pexpect.spawn but allows you to supply your own open file
  26. descriptor. For example, you could use it to read through a file looking
  27. for patterns, or to control a modem or serial device. '''
  28. def __init__ (self, fd, args=None, timeout=30, maxread=2000, searchwindowsize=None,
  29. logfile=None, encoding=None, codec_errors='strict'):
  30. '''This takes a file descriptor (an int) or an object that support the
  31. fileno() method (returning an int). All Python file-like objects
  32. support fileno(). '''
  33. if type(fd) != type(0) and hasattr(fd, 'fileno'):
  34. fd = fd.fileno()
  35. if type(fd) != type(0):
  36. raise ExceptionPexpect('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')
  37. try: # make sure fd is a valid file descriptor
  38. os.fstat(fd)
  39. except OSError:
  40. raise ExceptionPexpect('The fd argument is not a valid file descriptor.')
  41. self.args = None
  42. self.command = None
  43. SpawnBase.__init__(self, timeout, maxread, searchwindowsize, logfile,
  44. encoding=encoding, codec_errors=codec_errors)
  45. self.child_fd = fd
  46. self.own_fd = False
  47. self.closed = False
  48. self.name = '<file descriptor %d>' % fd
  49. def close (self):
  50. """Close the file descriptor.
  51. Calling this method a second time does nothing, but if the file
  52. descriptor was closed elsewhere, :class:`OSError` will be raised.
  53. """
  54. if self.child_fd == -1:
  55. return
  56. self.flush()
  57. os.close(self.child_fd)
  58. self.child_fd = -1
  59. self.closed = True
  60. def isalive (self):
  61. '''This checks if the file descriptor is still valid. If :func:`os.fstat`
  62. does not raise an exception then we assume it is alive. '''
  63. if self.child_fd == -1:
  64. return False
  65. try:
  66. os.fstat(self.child_fd)
  67. return True
  68. except:
  69. return False
  70. def terminate (self, force=False): # pragma: no cover
  71. '''Deprecated and invalid. Just raises an exception.'''
  72. raise ExceptionPexpect('This method is not valid for file descriptors.')
  73. # These four methods are left around for backwards compatibility, but not
  74. # documented as part of fdpexpect. You're encouraged to use os.write
  75. # directly.
  76. def send(self, s):
  77. "Write to fd, return number of bytes written"
  78. s = self._coerce_send_string(s)
  79. self._log(s, 'send')
  80. b = self._encoder.encode(s, final=False)
  81. return os.write(self.child_fd, b)
  82. def sendline(self, s):
  83. "Write to fd with trailing newline, return number of bytes written"
  84. s = self._coerce_send_string(s)
  85. return self.send(s + self.linesep)
  86. def write(self, s):
  87. "Write to fd, return None"
  88. self.send(s)
  89. def writelines(self, sequence):
  90. "Call self.write() for each item in sequence"
  91. for s in sequence:
  92. self.write(s)
  93. def read_nonblocking(self, size=1, timeout=-1):
  94. """
  95. Read from the file descriptor and return the result as a string.
  96. The read_nonblocking method of :class:`SpawnBase` assumes that a call
  97. to os.read will not block (timeout parameter is ignored). This is not
  98. the case for POSIX file-like objects such as sockets and serial ports.
  99. Use :func:`select.select`, timeout is implemented conditionally for
  100. POSIX systems.
  101. :param int size: Read at most *size* bytes.
  102. :param int timeout: Wait timeout seconds for file descriptor to be
  103. ready to read. When -1 (default), use self.timeout. When 0, poll.
  104. :return: String containing the bytes read
  105. """
  106. if os.name == 'posix':
  107. if timeout == -1:
  108. timeout = self.timeout
  109. rlist = [self.child_fd]
  110. wlist = []
  111. xlist = []
  112. rlist, wlist, xlist = select_ignore_interrupts(rlist, wlist, xlist, timeout)
  113. if self.child_fd not in rlist:
  114. raise TIMEOUT('Timeout exceeded.')
  115. return super(fdspawn, self).read_nonblocking(size)