spawnbase.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import codecs
  2. import os
  3. import sys
  4. import re
  5. import errno
  6. from .exceptions import ExceptionPexpect, EOF, TIMEOUT
  7. from .expect import Expecter, searcher_string, searcher_re
  8. PY3 = (sys.version_info[0] >= 3)
  9. text_type = str if PY3 else unicode
  10. class _NullCoder(object):
  11. """Pass bytes through unchanged."""
  12. @staticmethod
  13. def encode(b, final=False):
  14. return b
  15. @staticmethod
  16. def decode(b, final=False):
  17. return b
  18. class SpawnBase(object):
  19. """A base class providing the backwards-compatible spawn API for Pexpect.
  20. This should not be instantiated directly: use :class:`pexpect.spawn` or
  21. :class:`pexpect.fdpexpect.fdspawn`.
  22. """
  23. encoding = None
  24. pid = None
  25. flag_eof = False
  26. def __init__(self, timeout=30, maxread=2000, searchwindowsize=None,
  27. logfile=None, encoding=None, codec_errors='strict'):
  28. self.stdin = sys.stdin
  29. self.stdout = sys.stdout
  30. self.stderr = sys.stderr
  31. self.searcher = None
  32. self.ignorecase = False
  33. self.before = None
  34. self.after = None
  35. self.match = None
  36. self.match_index = None
  37. self.terminated = True
  38. self.exitstatus = None
  39. self.signalstatus = None
  40. # status returned by os.waitpid
  41. self.status = None
  42. # the child file descriptor is initially closed
  43. self.child_fd = -1
  44. self.timeout = timeout
  45. self.delimiter = EOF
  46. self.logfile = logfile
  47. # input from child (read_nonblocking)
  48. self.logfile_read = None
  49. # output to send (send, sendline)
  50. self.logfile_send = None
  51. # max bytes to read at one time into buffer
  52. self.maxread = maxread
  53. # This is the read buffer. See maxread.
  54. self.buffer = bytes() if (encoding is None) else text_type()
  55. # Data before searchwindowsize point is preserved, but not searched.
  56. self.searchwindowsize = searchwindowsize
  57. # Delay used before sending data to child. Time in seconds.
  58. # Set this to None to skip the time.sleep() call completely.
  59. self.delaybeforesend = 0.05
  60. # Used by close() to give kernel time to update process status.
  61. # Time in seconds.
  62. self.delayafterclose = 0.1
  63. # Used by terminate() to give kernel time to update process status.
  64. # Time in seconds.
  65. self.delayafterterminate = 0.1
  66. # Delay in seconds to sleep after each call to read_nonblocking().
  67. # Set this to None to skip the time.sleep() call completely: that
  68. # would restore the behavior from pexpect-2.0 (for performance
  69. # reasons or because you don't want to release Python's global
  70. # interpreter lock).
  71. self.delayafterread = 0.0001
  72. self.softspace = False
  73. self.name = '<' + repr(self) + '>'
  74. self.closed = True
  75. # Unicode interface
  76. self.encoding = encoding
  77. self.codec_errors = codec_errors
  78. if encoding is None:
  79. # bytes mode (accepts some unicode for backwards compatibility)
  80. self._encoder = self._decoder = _NullCoder()
  81. self.string_type = bytes
  82. self.crlf = b'\r\n'
  83. if PY3:
  84. self.allowed_string_types = (bytes, str)
  85. self.linesep = os.linesep.encode('ascii')
  86. def write_to_stdout(b):
  87. try:
  88. return sys.stdout.buffer.write(b)
  89. except AttributeError:
  90. # If stdout has been replaced, it may not have .buffer
  91. return sys.stdout.write(b.decode('ascii', 'replace'))
  92. self.write_to_stdout = write_to_stdout
  93. else:
  94. self.allowed_string_types = (basestring,) # analysis:ignore
  95. self.linesep = os.linesep
  96. self.write_to_stdout = sys.stdout.write
  97. else:
  98. # unicode mode
  99. self._encoder = codecs.getincrementalencoder(encoding)(codec_errors)
  100. self._decoder = codecs.getincrementaldecoder(encoding)(codec_errors)
  101. self.string_type = text_type
  102. self.crlf = u'\r\n'
  103. self.allowed_string_types = (text_type, )
  104. if PY3:
  105. self.linesep = os.linesep
  106. else:
  107. self.linesep = os.linesep.decode('ascii')
  108. # This can handle unicode in both Python 2 and 3
  109. self.write_to_stdout = sys.stdout.write
  110. def _log(self, s, direction):
  111. if self.logfile is not None:
  112. self.logfile.write(s)
  113. self.logfile.flush()
  114. second_log = self.logfile_send if (direction=='send') else self.logfile_read
  115. if second_log is not None:
  116. second_log.write(s)
  117. second_log.flush()
  118. # For backwards compatibility, in bytes mode (when encoding is None)
  119. # unicode is accepted for send and expect. Unicode mode is strictly unicode
  120. # only.
  121. def _coerce_expect_string(self, s):
  122. if self.encoding is None and not isinstance(s, bytes):
  123. return s.encode('ascii')
  124. return s
  125. def _coerce_send_string(self, s):
  126. if self.encoding is None and not isinstance(s, bytes):
  127. return s.encode('utf-8')
  128. return s
  129. def read_nonblocking(self, size=1, timeout=None):
  130. """This reads data from the file descriptor.
  131. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
  132. The timeout parameter is ignored.
  133. """
  134. try:
  135. s = os.read(self.child_fd, size)
  136. except OSError as err:
  137. if err.args[0] == errno.EIO:
  138. # Linux-style EOF
  139. self.flag_eof = True
  140. raise EOF('End Of File (EOF). Exception style platform.')
  141. raise
  142. if s == b'':
  143. # BSD-style EOF
  144. self.flag_eof = True
  145. raise EOF('End Of File (EOF). Empty string style platform.')
  146. s = self._decoder.decode(s, final=False)
  147. self._log(s, 'read')
  148. return s
  149. def _pattern_type_err(self, pattern):
  150. raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one'
  151. ' of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUT'\
  152. .format(badtype=type(pattern),
  153. badobj=pattern,
  154. goodtypes=', '.join([str(ast)\
  155. for ast in self.allowed_string_types])
  156. )
  157. )
  158. def compile_pattern_list(self, patterns):
  159. '''This compiles a pattern-string or a list of pattern-strings.
  160. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
  161. those. Patterns may also be None which results in an empty list (you
  162. might do this if waiting for an EOF or TIMEOUT condition without
  163. expecting any pattern).
  164. This is used by expect() when calling expect_list(). Thus expect() is
  165. nothing more than::
  166. cpl = self.compile_pattern_list(pl)
  167. return self.expect_list(cpl, timeout)
  168. If you are using expect() within a loop it may be more
  169. efficient to compile the patterns first and then call expect_list().
  170. This avoid calls in a loop to compile_pattern_list()::
  171. cpl = self.compile_pattern_list(my_pattern)
  172. while some_condition:
  173. ...
  174. i = self.expect_list(cpl, timeout)
  175. ...
  176. '''
  177. if patterns is None:
  178. return []
  179. if not isinstance(patterns, list):
  180. patterns = [patterns]
  181. # Allow dot to match \n
  182. compile_flags = re.DOTALL
  183. if self.ignorecase:
  184. compile_flags = compile_flags | re.IGNORECASE
  185. compiled_pattern_list = []
  186. for idx, p in enumerate(patterns):
  187. if isinstance(p, self.allowed_string_types):
  188. p = self._coerce_expect_string(p)
  189. compiled_pattern_list.append(re.compile(p, compile_flags))
  190. elif p is EOF:
  191. compiled_pattern_list.append(EOF)
  192. elif p is TIMEOUT:
  193. compiled_pattern_list.append(TIMEOUT)
  194. elif isinstance(p, type(re.compile(''))):
  195. compiled_pattern_list.append(p)
  196. else:
  197. self._pattern_type_err(p)
  198. return compiled_pattern_list
  199. def expect(self, pattern, timeout=-1, searchwindowsize=-1, async=False):
  200. '''This seeks through the stream until a pattern is matched. The
  201. pattern is overloaded and may take several types. The pattern can be a
  202. StringType, EOF, a compiled re, or a list of any of those types.
  203. Strings will be compiled to re types. This returns the index into the
  204. pattern list. If the pattern was not a list this returns index 0 on a
  205. successful match. This may raise exceptions for EOF or TIMEOUT. To
  206. avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
  207. list. That will cause expect to match an EOF or TIMEOUT condition
  208. instead of raising an exception.
  209. If you pass a list of patterns and more than one matches, the first
  210. match in the stream is chosen. If more than one pattern matches at that
  211. point, the leftmost in the pattern list is chosen. For example::
  212. # the input is 'foobar'
  213. index = p.expect(['bar', 'foo', 'foobar'])
  214. # returns 1('foo') even though 'foobar' is a "better" match
  215. Please note, however, that buffering can affect this behavior, since
  216. input arrives in unpredictable chunks. For example::
  217. # the input is 'foobar'
  218. index = p.expect(['foobar', 'foo'])
  219. # returns 0('foobar') if all input is available at once,
  220. # but returs 1('foo') if parts of the final 'bar' arrive late
  221. When a match is found for the given pattern, the class instance
  222. attribute *match* becomes an re.MatchObject result. Should an EOF
  223. or TIMEOUT pattern match, then the match attribute will be an instance
  224. of that exception class. The pairing before and after class
  225. instance attributes are views of the data preceding and following
  226. the matching pattern. On general exception, class attribute
  227. *before* is all data received up to the exception, while *match* and
  228. *after* attributes are value None.
  229. When the keyword argument timeout is -1 (default), then TIMEOUT will
  230. raise after the default value specified by the class timeout
  231. attribute. When None, TIMEOUT will not be raised and may block
  232. indefinitely until match.
  233. When the keyword argument searchwindowsize is -1 (default), then the
  234. value specified by the class maxread attribute is used.
  235. A list entry may be EOF or TIMEOUT instead of a string. This will
  236. catch these exceptions and return the index of the list entry instead
  237. of raising the exception. The attribute 'after' will be set to the
  238. exception type. The attribute 'match' will be None. This allows you to
  239. write code like this::
  240. index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
  241. if index == 0:
  242. do_something()
  243. elif index == 1:
  244. do_something_else()
  245. elif index == 2:
  246. do_some_other_thing()
  247. elif index == 3:
  248. do_something_completely_different()
  249. instead of code like this::
  250. try:
  251. index = p.expect(['good', 'bad'])
  252. if index == 0:
  253. do_something()
  254. elif index == 1:
  255. do_something_else()
  256. except EOF:
  257. do_some_other_thing()
  258. except TIMEOUT:
  259. do_something_completely_different()
  260. These two forms are equivalent. It all depends on what you want. You
  261. can also just expect the EOF if you are waiting for all output of a
  262. child to finish. For example::
  263. p = pexpect.spawn('/bin/ls')
  264. p.expect(pexpect.EOF)
  265. print p.before
  266. If you are trying to optimize for speed then see expect_list().
  267. On Python 3.4, or Python 3.3 with asyncio installed, passing
  268. ``async=True`` will make this return an :mod:`asyncio` coroutine,
  269. which you can yield from to get the same result that this method would
  270. normally give directly. So, inside a coroutine, you can replace this code::
  271. index = p.expect(patterns)
  272. With this non-blocking form::
  273. index = yield from p.expect(patterns, async=True)
  274. '''
  275. compiled_pattern_list = self.compile_pattern_list(pattern)
  276. return self.expect_list(compiled_pattern_list,
  277. timeout, searchwindowsize, async)
  278. def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1,
  279. async=False):
  280. '''This takes a list of compiled regular expressions and returns the
  281. index into the pattern_list that matched the child output. The list may
  282. also contain EOF or TIMEOUT(which are not compiled regular
  283. expressions). This method is similar to the expect() method except that
  284. expect_list() does not recompile the pattern list on every call. This
  285. may help if you are trying to optimize for speed, otherwise just use
  286. the expect() method. This is called by expect().
  287. Like :meth:`expect`, passing ``async=True`` will make this return an
  288. asyncio coroutine.
  289. '''
  290. if timeout == -1:
  291. timeout = self.timeout
  292. exp = Expecter(self, searcher_re(pattern_list), searchwindowsize)
  293. if async:
  294. from .async import expect_async
  295. return expect_async(exp, timeout)
  296. else:
  297. return exp.expect_loop(timeout)
  298. def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1,
  299. async=False):
  300. '''This is similar to expect(), but uses plain string matching instead
  301. of compiled regular expressions in 'pattern_list'. The 'pattern_list'
  302. may be a string; a list or other sequence of strings; or TIMEOUT and
  303. EOF.
  304. This call might be faster than expect() for two reasons: string
  305. searching is faster than RE matching and it is possible to limit the
  306. search to just the end of the input buffer.
  307. This method is also useful when you don't want to have to worry about
  308. escaping regular expression characters that you want to match.
  309. Like :meth:`expect`, passing ``async=True`` will make this return an
  310. asyncio coroutine.
  311. '''
  312. if timeout == -1:
  313. timeout = self.timeout
  314. if (isinstance(pattern_list, self.allowed_string_types) or
  315. pattern_list in (TIMEOUT, EOF)):
  316. pattern_list = [pattern_list]
  317. def prepare_pattern(pattern):
  318. if pattern in (TIMEOUT, EOF):
  319. return pattern
  320. if isinstance(pattern, self.allowed_string_types):
  321. return self._coerce_expect_string(pattern)
  322. self._pattern_type_err(pattern)
  323. try:
  324. pattern_list = iter(pattern_list)
  325. except TypeError:
  326. self._pattern_type_err(pattern_list)
  327. pattern_list = [prepare_pattern(p) for p in pattern_list]
  328. exp = Expecter(self, searcher_string(pattern_list), searchwindowsize)
  329. if async:
  330. from .async import expect_async
  331. return expect_async(exp, timeout)
  332. else:
  333. return exp.expect_loop(timeout)
  334. def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
  335. '''This is the common loop used inside expect. The 'searcher' should be
  336. an instance of searcher_re or searcher_string, which describes how and
  337. what to search for in the input.
  338. See expect() for other arguments, return value and exceptions. '''
  339. exp = Expecter(self, searcher, searchwindowsize)
  340. return exp.expect_loop(timeout)
  341. def read(self, size=-1):
  342. '''This reads at most "size" bytes from the file (less if the read hits
  343. EOF before obtaining size bytes). If the size argument is negative or
  344. omitted, read all data until EOF is reached. The bytes are returned as
  345. a string object. An empty string is returned when EOF is encountered
  346. immediately. '''
  347. if size == 0:
  348. return self.string_type()
  349. if size < 0:
  350. # delimiter default is EOF
  351. self.expect(self.delimiter)
  352. return self.before
  353. # I could have done this more directly by not using expect(), but
  354. # I deliberately decided to couple read() to expect() so that
  355. # I would catch any bugs early and ensure consistant behavior.
  356. # It's a little less efficient, but there is less for me to
  357. # worry about if I have to later modify read() or expect().
  358. # Note, it's OK if size==-1 in the regex. That just means it
  359. # will never match anything in which case we stop only on EOF.
  360. cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL)
  361. # delimiter default is EOF
  362. index = self.expect([cre, self.delimiter])
  363. if index == 0:
  364. ### FIXME self.before should be ''. Should I assert this?
  365. return self.after
  366. return self.before
  367. def readline(self, size=-1):
  368. '''This reads and returns one entire line. The newline at the end of
  369. line is returned as part of the string, unless the file ends without a
  370. newline. An empty string is returned if EOF is encountered immediately.
  371. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
  372. this is what the pseudotty device returns. So contrary to what you may
  373. expect you will receive newlines as \\r\\n.
  374. If the size argument is 0 then an empty string is returned. In all
  375. other cases the size argument is ignored, which is not standard
  376. behavior for a file-like object. '''
  377. if size == 0:
  378. return self.string_type()
  379. # delimiter default is EOF
  380. index = self.expect([self.crlf, self.delimiter])
  381. if index == 0:
  382. return self.before + self.crlf
  383. else:
  384. return self.before
  385. def __iter__(self):
  386. '''This is to support iterators over a file-like object.
  387. '''
  388. return iter(self.readline, self.string_type())
  389. def readlines(self, sizehint=-1):
  390. '''This reads until EOF using readline() and returns a list containing
  391. the lines thus read. The optional 'sizehint' argument is ignored.
  392. Remember, because this reads until EOF that means the child
  393. process should have closed its stdout. If you run this method on
  394. a child that is still running with its stdout open then this
  395. method will block until it timesout.'''
  396. lines = []
  397. while True:
  398. line = self.readline()
  399. if not line:
  400. break
  401. lines.append(line)
  402. return lines
  403. def fileno(self):
  404. '''Expose file descriptor for a file-like interface
  405. '''
  406. return self.child_fd
  407. def flush(self):
  408. '''This does nothing. It is here to support the interface for a
  409. File-like object. '''
  410. pass
  411. def isatty(self):
  412. """Overridden in subclass using tty"""
  413. return False
  414. # For 'with spawn(...) as child:'
  415. def __enter__(self):
  416. return self
  417. def __exit__(self, etype, evalue, tb):
  418. # We rely on subclasses to implement close(). If they don't, it's not
  419. # clear what a context manager should do.
  420. self.close()