You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

148 lines
5.7 KiB

4 years ago
  1. '''This is like pexpect, but it will work with any file descriptor that you
  2. pass it. You are responsible 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, poll_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', use_poll=False):
  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. self.use_poll = use_poll
  50. def close (self):
  51. """Close the file descriptor.
  52. Calling this method a second time does nothing, but if the file
  53. descriptor was closed elsewhere, :class:`OSError` will be raised.
  54. """
  55. if self.child_fd == -1:
  56. return
  57. self.flush()
  58. os.close(self.child_fd)
  59. self.child_fd = -1
  60. self.closed = True
  61. def isalive (self):
  62. '''This checks if the file descriptor is still valid. If :func:`os.fstat`
  63. does not raise an exception then we assume it is alive. '''
  64. if self.child_fd == -1:
  65. return False
  66. try:
  67. os.fstat(self.child_fd)
  68. return True
  69. except:
  70. return False
  71. def terminate (self, force=False): # pragma: no cover
  72. '''Deprecated and invalid. Just raises an exception.'''
  73. raise ExceptionPexpect('This method is not valid for file descriptors.')
  74. # These four methods are left around for backwards compatibility, but not
  75. # documented as part of fdpexpect. You're encouraged to use os.write
  76. # directly.
  77. def send(self, s):
  78. "Write to fd, return number of bytes written"
  79. s = self._coerce_send_string(s)
  80. self._log(s, 'send')
  81. b = self._encoder.encode(s, final=False)
  82. return os.write(self.child_fd, b)
  83. def sendline(self, s):
  84. "Write to fd with trailing newline, return number of bytes written"
  85. s = self._coerce_send_string(s)
  86. return self.send(s + self.linesep)
  87. def write(self, s):
  88. "Write to fd, return None"
  89. self.send(s)
  90. def writelines(self, sequence):
  91. "Call self.write() for each item in sequence"
  92. for s in sequence:
  93. self.write(s)
  94. def read_nonblocking(self, size=1, timeout=-1):
  95. """
  96. Read from the file descriptor and return the result as a string.
  97. The read_nonblocking method of :class:`SpawnBase` assumes that a call
  98. to os.read will not block (timeout parameter is ignored). This is not
  99. the case for POSIX file-like objects such as sockets and serial ports.
  100. Use :func:`select.select`, timeout is implemented conditionally for
  101. POSIX systems.
  102. :param int size: Read at most *size* bytes.
  103. :param int timeout: Wait timeout seconds for file descriptor to be
  104. ready to read. When -1 (default), use self.timeout. When 0, poll.
  105. :return: String containing the bytes read
  106. """
  107. if os.name == 'posix':
  108. if timeout == -1:
  109. timeout = self.timeout
  110. rlist = [self.child_fd]
  111. wlist = []
  112. xlist = []
  113. if self.use_poll:
  114. rlist = poll_ignore_interrupts(rlist, timeout)
  115. else:
  116. rlist, wlist, xlist = select_ignore_interrupts(
  117. rlist, wlist, xlist, timeout
  118. )
  119. if self.child_fd not in rlist:
  120. raise TIMEOUT('Timeout exceeded.')
  121. return super(fdspawn, self).read_nonblocking(size)