pty_spawn.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. import os
  2. import sys
  3. import time
  4. import pty
  5. import tty
  6. import errno
  7. import signal
  8. from contextlib import contextmanager
  9. import ptyprocess
  10. from ptyprocess.ptyprocess import use_native_pty_fork
  11. from .exceptions import ExceptionPexpect, EOF, TIMEOUT
  12. from .spawnbase import SpawnBase
  13. from .utils import which, split_command_line, select_ignore_interrupts
  14. @contextmanager
  15. def _wrap_ptyprocess_err():
  16. """Turn ptyprocess errors into our own ExceptionPexpect errors"""
  17. try:
  18. yield
  19. except ptyprocess.PtyProcessError as e:
  20. raise ExceptionPexpect(*e.args)
  21. PY3 = (sys.version_info[0] >= 3)
  22. class spawn(SpawnBase):
  23. '''This is the main class interface for Pexpect. Use this class to start
  24. and control child applications. '''
  25. # This is purely informational now - changing it has no effect
  26. use_native_pty_fork = use_native_pty_fork
  27. def __init__(self, command, args=[], timeout=30, maxread=2000,
  28. searchwindowsize=None, logfile=None, cwd=None, env=None,
  29. ignore_sighup=False, echo=True, preexec_fn=None,
  30. encoding=None, codec_errors='strict', dimensions=None):
  31. '''This is the constructor. The command parameter may be a string that
  32. includes a command and any arguments to the command. For example::
  33. child = pexpect.spawn('/usr/bin/ftp')
  34. child = pexpect.spawn('/usr/bin/ssh user@example.com')
  35. child = pexpect.spawn('ls -latr /tmp')
  36. You may also construct it with a list of arguments like so::
  37. child = pexpect.spawn('/usr/bin/ftp', [])
  38. child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
  39. child = pexpect.spawn('ls', ['-latr', '/tmp'])
  40. After this the child application will be created and will be ready to
  41. talk to. For normal use, see expect() and send() and sendline().
  42. Remember that Pexpect does NOT interpret shell meta characters such as
  43. redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
  44. common mistake. If you want to run a command and pipe it through
  45. another command then you must also start a shell. For example::
  46. child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
  47. child.expect(pexpect.EOF)
  48. The second form of spawn (where you pass a list of arguments) is useful
  49. in situations where you wish to spawn a command and pass it its own
  50. argument list. This can make syntax more clear. For example, the
  51. following is equivalent to the previous example::
  52. shell_cmd = 'ls -l | grep LOG > logs.txt'
  53. child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
  54. child.expect(pexpect.EOF)
  55. The maxread attribute sets the read buffer size. This is maximum number
  56. of bytes that Pexpect will try to read from a TTY at one time. Setting
  57. the maxread size to 1 will turn off buffering. Setting the maxread
  58. value higher may help performance in cases where large amounts of
  59. output are read back from the child. This feature is useful in
  60. conjunction with searchwindowsize.
  61. When the keyword argument *searchwindowsize* is None (default), the
  62. full buffer is searched at each iteration of receiving incoming data.
  63. The default number of bytes scanned at each iteration is very large
  64. and may be reduced to collaterally reduce search cost. After
  65. :meth:`~.expect` returns, the full buffer attribute remains up to
  66. size *maxread* irrespective of *searchwindowsize* value.
  67. When the keyword argument ``timeout`` is specified as a number,
  68. (default: *30*), then :class:`TIMEOUT` will be raised after the value
  69. specified has elapsed, in seconds, for any of the :meth:`~.expect`
  70. family of method calls. When None, TIMEOUT will not be raised, and
  71. :meth:`~.expect` may block indefinitely until match.
  72. The logfile member turns on or off logging. All input and output will
  73. be copied to the given file object. Set logfile to None to stop
  74. logging. This is the default. Set logfile to sys.stdout to echo
  75. everything to standard output. The logfile is flushed after each write.
  76. Example log input and output to a file::
  77. child = pexpect.spawn('some_command')
  78. fout = open('mylog.txt','wb')
  79. child.logfile = fout
  80. Example log to stdout::
  81. # In Python 2:
  82. child = pexpect.spawn('some_command')
  83. child.logfile = sys.stdout
  84. # In Python 3, spawnu should be used to give str to stdout:
  85. child = pexpect.spawnu('some_command')
  86. child.logfile = sys.stdout
  87. The logfile_read and logfile_send members can be used to separately log
  88. the input from the child and output sent to the child. Sometimes you
  89. don't want to see everything you write to the child. You only want to
  90. log what the child sends back. For example::
  91. child = pexpect.spawn('some_command')
  92. child.logfile_read = sys.stdout
  93. You will need to pass an encoding to spawn in the above code if you are
  94. using Python 3.
  95. To separately log output sent to the child use logfile_send::
  96. child.logfile_send = fout
  97. If ``ignore_sighup`` is True, the child process will ignore SIGHUP
  98. signals. The default is False from Pexpect 4.0, meaning that SIGHUP
  99. will be handled normally by the child.
  100. The delaybeforesend helps overcome a weird behavior that many users
  101. were experiencing. The typical problem was that a user would expect() a
  102. "Password:" prompt and then immediately call sendline() to send the
  103. password. The user would then see that their password was echoed back
  104. to them. Passwords don't normally echo. The problem is caused by the
  105. fact that most applications print out the "Password" prompt and then
  106. turn off stdin echo, but if you send your password before the
  107. application turned off echo, then you get your password echoed.
  108. Normally this wouldn't be a problem when interacting with a human at a
  109. real keyboard. If you introduce a slight delay just before writing then
  110. this seems to clear up the problem. This was such a common problem for
  111. many users that I decided that the default pexpect behavior should be
  112. to sleep just before writing to the child application. 1/20th of a
  113. second (50 ms) seems to be enough to clear up the problem. You can set
  114. delaybeforesend to None to return to the old behavior.
  115. Note that spawn is clever about finding commands on your path.
  116. It uses the same logic that "which" uses to find executables.
  117. If you wish to get the exit status of the child you must call the
  118. close() method. The exit or signal status of the child will be stored
  119. in self.exitstatus or self.signalstatus. If the child exited normally
  120. then exitstatus will store the exit return code and signalstatus will
  121. be None. If the child was terminated abnormally with a signal then
  122. signalstatus will store the signal value and exitstatus will be None::
  123. child = pexpect.spawn('some_command')
  124. child.close()
  125. print(child.exitstatus, child.signalstatus)
  126. If you need more detail you can also read the self.status member which
  127. stores the status returned by os.waitpid. You can interpret this using
  128. os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
  129. The echo attribute may be set to False to disable echoing of input.
  130. As a pseudo-terminal, all input echoed by the "keyboard" (send()
  131. or sendline()) will be repeated to output. For many cases, it is
  132. not desirable to have echo enabled, and it may be later disabled
  133. using setecho(False) followed by waitnoecho(). However, for some
  134. platforms such as Solaris, this is not possible, and should be
  135. disabled immediately on spawn.
  136. If preexec_fn is given, it will be called in the child process before
  137. launching the given command. This is useful to e.g. reset inherited
  138. signal handlers.
  139. The dimensions attribute specifies the size of the pseudo-terminal as
  140. seen by the subprocess, and is specified as a two-entry tuple (rows,
  141. columns). If this is unspecified, the defaults in ptyprocess will apply.
  142. '''
  143. super(spawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize,
  144. logfile=logfile, encoding=encoding, codec_errors=codec_errors)
  145. self.STDIN_FILENO = pty.STDIN_FILENO
  146. self.STDOUT_FILENO = pty.STDOUT_FILENO
  147. self.STDERR_FILENO = pty.STDERR_FILENO
  148. self.cwd = cwd
  149. self.env = env
  150. self.echo = echo
  151. self.ignore_sighup = ignore_sighup
  152. self.__irix_hack = sys.platform.lower().startswith('irix')
  153. if command is None:
  154. self.command = None
  155. self.args = None
  156. self.name = '<pexpect factory incomplete>'
  157. else:
  158. self._spawn(command, args, preexec_fn, dimensions)
  159. def __str__(self):
  160. '''This returns a human-readable string that represents the state of
  161. the object. '''
  162. s = []
  163. s.append(repr(self))
  164. s.append('command: ' + str(self.command))
  165. s.append('args: %r' % (self.args,))
  166. s.append('buffer (last 100 chars): %r' % (
  167. self.buffer[-100:] if self.buffer else self.buffer,))
  168. s.append('before (last 100 chars): %r' % (
  169. self.before[-100:] if self.before else self.before,))
  170. s.append('after: %r' % (self.after,))
  171. s.append('match: %r' % (self.match,))
  172. s.append('match_index: ' + str(self.match_index))
  173. s.append('exitstatus: ' + str(self.exitstatus))
  174. if hasattr(self, 'ptyproc'):
  175. s.append('flag_eof: ' + str(self.flag_eof))
  176. s.append('pid: ' + str(self.pid))
  177. s.append('child_fd: ' + str(self.child_fd))
  178. s.append('closed: ' + str(self.closed))
  179. s.append('timeout: ' + str(self.timeout))
  180. s.append('delimiter: ' + str(self.delimiter))
  181. s.append('logfile: ' + str(self.logfile))
  182. s.append('logfile_read: ' + str(self.logfile_read))
  183. s.append('logfile_send: ' + str(self.logfile_send))
  184. s.append('maxread: ' + str(self.maxread))
  185. s.append('ignorecase: ' + str(self.ignorecase))
  186. s.append('searchwindowsize: ' + str(self.searchwindowsize))
  187. s.append('delaybeforesend: ' + str(self.delaybeforesend))
  188. s.append('delayafterclose: ' + str(self.delayafterclose))
  189. s.append('delayafterterminate: ' + str(self.delayafterterminate))
  190. return '\n'.join(s)
  191. def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
  192. '''This starts the given command in a child process. This does all the
  193. fork/exec type of stuff for a pty. This is called by __init__. If args
  194. is empty then command will be parsed (split on spaces) and args will be
  195. set to parsed arguments. '''
  196. # The pid and child_fd of this object get set by this method.
  197. # Note that it is difficult for this method to fail.
  198. # You cannot detect if the child process cannot start.
  199. # So the only way you can tell if the child process started
  200. # or not is to try to read from the file descriptor. If you get
  201. # EOF immediately then it means that the child is already dead.
  202. # That may not necessarily be bad because you may have spawned a child
  203. # that performs some task; creates no stdout output; and then dies.
  204. # If command is an int type then it may represent a file descriptor.
  205. if isinstance(command, type(0)):
  206. raise ExceptionPexpect('Command is an int type. ' +
  207. 'If this is a file descriptor then maybe you want to ' +
  208. 'use fdpexpect.fdspawn which takes an existing ' +
  209. 'file descriptor instead of a command string.')
  210. if not isinstance(args, type([])):
  211. raise TypeError('The argument, args, must be a list.')
  212. if args == []:
  213. self.args = split_command_line(command)
  214. self.command = self.args[0]
  215. else:
  216. # Make a shallow copy of the args list.
  217. self.args = args[:]
  218. self.args.insert(0, command)
  219. self.command = command
  220. command_with_path = which(self.command, env=self.env)
  221. if command_with_path is None:
  222. raise ExceptionPexpect('The command was not found or was not ' +
  223. 'executable: %s.' % self.command)
  224. self.command = command_with_path
  225. self.args[0] = self.command
  226. self.name = '<' + ' '.join(self.args) + '>'
  227. assert self.pid is None, 'The pid member must be None.'
  228. assert self.command is not None, 'The command member must not be None.'
  229. kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
  230. if self.ignore_sighup:
  231. def preexec_wrapper():
  232. "Set SIGHUP to be ignored, then call the real preexec_fn"
  233. signal.signal(signal.SIGHUP, signal.SIG_IGN)
  234. if preexec_fn is not None:
  235. preexec_fn()
  236. kwargs['preexec_fn'] = preexec_wrapper
  237. if dimensions is not None:
  238. kwargs['dimensions'] = dimensions
  239. if self.encoding is not None:
  240. # Encode command line using the specified encoding
  241. self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
  242. for a in self.args]
  243. self.ptyproc = self._spawnpty(self.args, env=self.env,
  244. cwd=self.cwd, **kwargs)
  245. self.pid = self.ptyproc.pid
  246. self.child_fd = self.ptyproc.fd
  247. self.terminated = False
  248. self.closed = False
  249. def _spawnpty(self, args, **kwargs):
  250. '''Spawn a pty and return an instance of PtyProcess.'''
  251. return ptyprocess.PtyProcess.spawn(args, **kwargs)
  252. def close(self, force=True):
  253. '''This closes the connection with the child application. Note that
  254. calling close() more than once is valid. This emulates standard Python
  255. behavior with files. Set force to True if you want to make sure that
  256. the child is terminated (SIGKILL is sent if the child ignores SIGHUP
  257. and SIGINT). '''
  258. self.flush()
  259. self.ptyproc.close(force=force)
  260. self.isalive() # Update exit status from ptyproc
  261. self.child_fd = -1
  262. def isatty(self):
  263. '''This returns True if the file descriptor is open and connected to a
  264. tty(-like) device, else False.
  265. On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
  266. the child pty may not appear as a terminal device. This means
  267. methods such as setecho(), setwinsize(), getwinsize() may raise an
  268. IOError. '''
  269. return os.isatty(self.child_fd)
  270. def waitnoecho(self, timeout=-1):
  271. '''This waits until the terminal ECHO flag is set False. This returns
  272. True if the echo mode is off. This returns False if the ECHO flag was
  273. not set False before the timeout. This can be used to detect when the
  274. child is waiting for a password. Usually a child application will turn
  275. off echo mode when it is waiting for the user to enter a password. For
  276. example, instead of expecting the "password:" prompt you can wait for
  277. the child to set ECHO off::
  278. p = pexpect.spawn('ssh user@example.com')
  279. p.waitnoecho()
  280. p.sendline(mypassword)
  281. If timeout==-1 then this method will use the value in self.timeout.
  282. If timeout==None then this method to block until ECHO flag is False.
  283. '''
  284. if timeout == -1:
  285. timeout = self.timeout
  286. if timeout is not None:
  287. end_time = time.time() + timeout
  288. while True:
  289. if not self.getecho():
  290. return True
  291. if timeout < 0 and timeout is not None:
  292. return False
  293. if timeout is not None:
  294. timeout = end_time - time.time()
  295. time.sleep(0.1)
  296. def getecho(self):
  297. '''This returns the terminal echo mode. This returns True if echo is
  298. on or False if echo is off. Child applications that are expecting you
  299. to enter a password often set ECHO False. See waitnoecho().
  300. Not supported on platforms where ``isatty()`` returns False. '''
  301. return self.ptyproc.getecho()
  302. def setecho(self, state):
  303. '''This sets the terminal echo mode on or off. Note that anything the
  304. child sent before the echo will be lost, so you should be sure that
  305. your input buffer is empty before you call setecho(). For example, the
  306. following will work as expected::
  307. p = pexpect.spawn('cat') # Echo is on by default.
  308. p.sendline('1234') # We expect see this twice from the child...
  309. p.expect(['1234']) # ... once from the tty echo...
  310. p.expect(['1234']) # ... and again from cat itself.
  311. p.setecho(False) # Turn off tty echo
  312. p.sendline('abcd') # We will set this only once (echoed by cat).
  313. p.sendline('wxyz') # We will set this only once (echoed by cat)
  314. p.expect(['abcd'])
  315. p.expect(['wxyz'])
  316. The following WILL NOT WORK because the lines sent before the setecho
  317. will be lost::
  318. p = pexpect.spawn('cat')
  319. p.sendline('1234')
  320. p.setecho(False) # Turn off tty echo
  321. p.sendline('abcd') # We will set this only once (echoed by cat).
  322. p.sendline('wxyz') # We will set this only once (echoed by cat)
  323. p.expect(['1234'])
  324. p.expect(['1234'])
  325. p.expect(['abcd'])
  326. p.expect(['wxyz'])
  327. Not supported on platforms where ``isatty()`` returns False.
  328. '''
  329. return self.ptyproc.setecho(state)
  330. def read_nonblocking(self, size=1, timeout=-1):
  331. '''This reads at most size characters from the child application. It
  332. includes a timeout. If the read does not complete within the timeout
  333. period then a TIMEOUT exception is raised. If the end of file is read
  334. then an EOF exception will be raised. If a logfile is specified, a
  335. copy is written to that log.
  336. If timeout is None then the read may block indefinitely.
  337. If timeout is -1 then the self.timeout value is used. If timeout is 0
  338. then the child is polled and if there is no data immediately ready
  339. then this will raise a TIMEOUT exception.
  340. The timeout refers only to the amount of time to read at least one
  341. character. This is not affected by the 'size' parameter, so if you call
  342. read_nonblocking(size=100, timeout=30) and only one character is
  343. available right away then one character will be returned immediately.
  344. It will not wait for 30 seconds for another 99 characters to come in.
  345. This is a wrapper around os.read(). It uses select.select() to
  346. implement the timeout. '''
  347. if self.closed:
  348. raise ValueError('I/O operation on closed file.')
  349. if timeout == -1:
  350. timeout = self.timeout
  351. # Note that some systems such as Solaris do not give an EOF when
  352. # the child dies. In fact, you can still try to read
  353. # from the child_fd -- it will block forever or until TIMEOUT.
  354. # For this case, I test isalive() before doing any reading.
  355. # If isalive() is false, then I pretend that this is the same as EOF.
  356. if not self.isalive():
  357. # timeout of 0 means "poll"
  358. r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
  359. if not r:
  360. self.flag_eof = True
  361. raise EOF('End Of File (EOF). Braindead platform.')
  362. elif self.__irix_hack:
  363. # Irix takes a long time before it realizes a child was terminated.
  364. # FIXME So does this mean Irix systems are forced to always have
  365. # FIXME a 2 second delay when calling read_nonblocking? That sucks.
  366. r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
  367. if not r and not self.isalive():
  368. self.flag_eof = True
  369. raise EOF('End Of File (EOF). Slow platform.')
  370. r, w, e = select_ignore_interrupts([self.child_fd], [], [], timeout)
  371. if not r:
  372. if not self.isalive():
  373. # Some platforms, such as Irix, will claim that their
  374. # processes are alive; timeout on the select; and
  375. # then finally admit that they are not alive.
  376. self.flag_eof = True
  377. raise EOF('End of File (EOF). Very slow platform.')
  378. else:
  379. raise TIMEOUT('Timeout exceeded.')
  380. if self.child_fd in r:
  381. return super(spawn, self).read_nonblocking(size)
  382. raise ExceptionPexpect('Reached an unexpected state.') # pragma: no cover
  383. def write(self, s):
  384. '''This is similar to send() except that there is no return value.
  385. '''
  386. self.send(s)
  387. def writelines(self, sequence):
  388. '''This calls write() for each element in the sequence. The sequence
  389. can be any iterable object producing strings, typically a list of
  390. strings. This does not add line separators. There is no return value.
  391. '''
  392. for s in sequence:
  393. self.write(s)
  394. def send(self, s):
  395. '''Sends string ``s`` to the child process, returning the number of
  396. bytes written. If a logfile is specified, a copy is written to that
  397. log.
  398. The default terminal input mode is canonical processing unless set
  399. otherwise by the child process. This allows backspace and other line
  400. processing to be performed prior to transmitting to the receiving
  401. program. As this is buffered, there is a limited size of such buffer.
  402. On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
  403. other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
  404. on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
  405. This value may be discovered using fpathconf(3)::
  406. >>> from os import fpathconf
  407. >>> print(fpathconf(0, 'PC_MAX_CANON'))
  408. 256
  409. On such a system, only 256 bytes may be received per line. Any
  410. subsequent bytes received will be discarded. BEL (``'\a'``) is then
  411. sent to output if IMAXBEL (termios.h) is set by the tty driver.
  412. This is usually enabled by default. Linux does not honor this as
  413. an option -- it behaves as though it is always set on.
  414. Canonical input processing may be disabled altogether by executing
  415. a shell, then stty(1), before executing the final program::
  416. >>> bash = pexpect.spawn('/bin/bash', echo=False)
  417. >>> bash.sendline('stty -icanon')
  418. >>> bash.sendline('base64')
  419. >>> bash.sendline('x' * 5000)
  420. '''
  421. if self.delaybeforesend is not None:
  422. time.sleep(self.delaybeforesend)
  423. s = self._coerce_send_string(s)
  424. self._log(s, 'send')
  425. b = self._encoder.encode(s, final=False)
  426. return os.write(self.child_fd, b)
  427. def sendline(self, s=''):
  428. '''Wraps send(), sending string ``s`` to child process, with
  429. ``os.linesep`` automatically appended. Returns number of bytes
  430. written. Only a limited number of bytes may be sent for each
  431. line in the default terminal mode, see docstring of :meth:`send`.
  432. '''
  433. s = self._coerce_send_string(s)
  434. return self.send(s + self.linesep)
  435. def _log_control(self, s):
  436. """Write control characters to the appropriate log files"""
  437. if self.encoding is not None:
  438. s = s.decode(self.encoding, 'replace')
  439. self._log(s, 'send')
  440. def sendcontrol(self, char):
  441. '''Helper method that wraps send() with mnemonic access for sending control
  442. character to the child (such as Ctrl-C or Ctrl-D). For example, to send
  443. Ctrl-G (ASCII 7, bell, '\a')::
  444. child.sendcontrol('g')
  445. See also, sendintr() and sendeof().
  446. '''
  447. n, byte = self.ptyproc.sendcontrol(char)
  448. self._log_control(byte)
  449. return n
  450. def sendeof(self):
  451. '''This sends an EOF to the child. This sends a character which causes
  452. the pending parent output buffer to be sent to the waiting child
  453. program without waiting for end-of-line. If it is the first character
  454. of the line, the read() in the user program returns 0, which signifies
  455. end-of-file. This means to work as expected a sendeof() has to be
  456. called at the beginning of a line. This method does not send a newline.
  457. It is the responsibility of the caller to ensure the eof is sent at the
  458. beginning of a line. '''
  459. n, byte = self.ptyproc.sendeof()
  460. self._log_control(byte)
  461. def sendintr(self):
  462. '''This sends a SIGINT to the child. It does not require
  463. the SIGINT to be the first character on a line. '''
  464. n, byte = self.ptyproc.sendintr()
  465. self._log_control(byte)
  466. @property
  467. def flag_eof(self):
  468. return self.ptyproc.flag_eof
  469. @flag_eof.setter
  470. def flag_eof(self, value):
  471. self.ptyproc.flag_eof = value
  472. def eof(self):
  473. '''This returns True if the EOF exception was ever raised.
  474. '''
  475. return self.flag_eof
  476. def terminate(self, force=False):
  477. '''This forces a child process to terminate. It starts nicely with
  478. SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
  479. returns True if the child was terminated. This returns False if the
  480. child could not be terminated. '''
  481. if not self.isalive():
  482. return True
  483. try:
  484. self.kill(signal.SIGHUP)
  485. time.sleep(self.delayafterterminate)
  486. if not self.isalive():
  487. return True
  488. self.kill(signal.SIGCONT)
  489. time.sleep(self.delayafterterminate)
  490. if not self.isalive():
  491. return True
  492. self.kill(signal.SIGINT)
  493. time.sleep(self.delayafterterminate)
  494. if not self.isalive():
  495. return True
  496. if force:
  497. self.kill(signal.SIGKILL)
  498. time.sleep(self.delayafterterminate)
  499. if not self.isalive():
  500. return True
  501. else:
  502. return False
  503. return False
  504. except OSError:
  505. # I think there are kernel timing issues that sometimes cause
  506. # this to happen. I think isalive() reports True, but the
  507. # process is dead to the kernel.
  508. # Make one last attempt to see if the kernel is up to date.
  509. time.sleep(self.delayafterterminate)
  510. if not self.isalive():
  511. return True
  512. else:
  513. return False
  514. def wait(self):
  515. '''This waits until the child exits. This is a blocking call. This will
  516. not read any data from the child, so this will block forever if the
  517. child has unread output and has terminated. In other words, the child
  518. may have printed output then called exit(), but, the child is
  519. technically still alive until its output is read by the parent.
  520. This method is non-blocking if :meth:`wait` has already been called
  521. previously or :meth:`isalive` method returns False. It simply returns
  522. the previously determined exit status.
  523. '''
  524. ptyproc = self.ptyproc
  525. with _wrap_ptyprocess_err():
  526. # exception may occur if "Is some other process attempting
  527. # "job control with our child pid?"
  528. exitstatus = ptyproc.wait()
  529. self.status = ptyproc.status
  530. self.exitstatus = ptyproc.exitstatus
  531. self.signalstatus = ptyproc.signalstatus
  532. self.terminated = True
  533. return exitstatus
  534. def isalive(self):
  535. '''This tests if the child process is running or not. This is
  536. non-blocking. If the child was terminated then this will read the
  537. exitstatus or signalstatus of the child. This returns True if the child
  538. process appears to be running or False if not. It can take literally
  539. SECONDS for Solaris to return the right status. '''
  540. ptyproc = self.ptyproc
  541. with _wrap_ptyprocess_err():
  542. alive = ptyproc.isalive()
  543. if not alive:
  544. self.status = ptyproc.status
  545. self.exitstatus = ptyproc.exitstatus
  546. self.signalstatus = ptyproc.signalstatus
  547. self.terminated = True
  548. return alive
  549. def kill(self, sig):
  550. '''This sends the given signal to the child application. In keeping
  551. with UNIX tradition it has a misleading name. It does not necessarily
  552. kill the child unless you send the right signal. '''
  553. # Same as os.kill, but the pid is given for you.
  554. if self.isalive():
  555. os.kill(self.pid, sig)
  556. def getwinsize(self):
  557. '''This returns the terminal window size of the child tty. The return
  558. value is a tuple of (rows, cols). '''
  559. return self.ptyproc.getwinsize()
  560. def setwinsize(self, rows, cols):
  561. '''This sets the terminal window size of the child tty. This will cause
  562. a SIGWINCH signal to be sent to the child. This does not change the
  563. physical window size. It changes the size reported to TTY-aware
  564. applications like vi or curses -- applications that respond to the
  565. SIGWINCH signal. '''
  566. return self.ptyproc.setwinsize(rows, cols)
  567. def interact(self, escape_character=chr(29),
  568. input_filter=None, output_filter=None):
  569. '''This gives control of the child process to the interactive user (the
  570. human at the keyboard). Keystrokes are sent to the child process, and
  571. the stdout and stderr output of the child process is printed. This
  572. simply echos the child stdout and child stderr to the real stdout and
  573. it echos the real stdin to the child stdin. When the user types the
  574. escape_character this method will return None. The escape_character
  575. will not be transmitted. The default for escape_character is
  576. entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
  577. escaping, escape_character may be set to None.
  578. If a logfile is specified, then the data sent and received from the
  579. child process in interact mode is duplicated to the given log.
  580. You may pass in optional input and output filter functions. These
  581. functions should take a string and return a string. The output_filter
  582. will be passed all the output from the child process. The input_filter
  583. will be passed all the keyboard input from the user. The input_filter
  584. is run BEFORE the check for the escape_character.
  585. Note that if you change the window size of the parent the SIGWINCH
  586. signal will not be passed through to the child. If you want the child
  587. window size to change when the parent's window size changes then do
  588. something like the following example::
  589. import pexpect, struct, fcntl, termios, signal, sys
  590. def sigwinch_passthrough (sig, data):
  591. s = struct.pack("HHHH", 0, 0, 0, 0)
  592. a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
  593. termios.TIOCGWINSZ , s))
  594. global p
  595. p.setwinsize(a[0],a[1])
  596. # Note this 'p' global and used in sigwinch_passthrough.
  597. p = pexpect.spawn('/bin/bash')
  598. signal.signal(signal.SIGWINCH, sigwinch_passthrough)
  599. p.interact()
  600. '''
  601. # Flush the buffer.
  602. self.write_to_stdout(self.buffer)
  603. self.stdout.flush()
  604. self.buffer = self.string_type()
  605. mode = tty.tcgetattr(self.STDIN_FILENO)
  606. tty.setraw(self.STDIN_FILENO)
  607. if escape_character is not None and PY3:
  608. escape_character = escape_character.encode('latin-1')
  609. try:
  610. self.__interact_copy(escape_character, input_filter, output_filter)
  611. finally:
  612. tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
  613. def __interact_writen(self, fd, data):
  614. '''This is used by the interact() method.
  615. '''
  616. while data != b'' and self.isalive():
  617. n = os.write(fd, data)
  618. data = data[n:]
  619. def __interact_read(self, fd):
  620. '''This is used by the interact() method.
  621. '''
  622. return os.read(fd, 1000)
  623. def __interact_copy(self, escape_character=None,
  624. input_filter=None, output_filter=None):
  625. '''This is used by the interact() method.
  626. '''
  627. while self.isalive():
  628. r, w, e = select_ignore_interrupts([self.child_fd, self.STDIN_FILENO], [], [])
  629. if self.child_fd in r:
  630. try:
  631. data = self.__interact_read(self.child_fd)
  632. except OSError as err:
  633. if err.args[0] == errno.EIO:
  634. # Linux-style EOF
  635. break
  636. raise
  637. if data == b'':
  638. # BSD-style EOF
  639. break
  640. if output_filter:
  641. data = output_filter(data)
  642. self._log(data, 'read')
  643. os.write(self.STDOUT_FILENO, data)
  644. if self.STDIN_FILENO in r:
  645. data = self.__interact_read(self.STDIN_FILENO)
  646. if input_filter:
  647. data = input_filter(data)
  648. i = -1
  649. if escape_character is not None:
  650. i = data.rfind(escape_character)
  651. if i != -1:
  652. data = data[:i]
  653. if data:
  654. self._log(data, 'send')
  655. self.__interact_writen(self.child_fd, data)
  656. break
  657. self._log(data, 'send')
  658. self.__interact_writen(self.child_fd, data)
  659. def spawnu(*args, **kwargs):
  660. """Deprecated: pass encoding to spawn() instead."""
  661. kwargs.setdefault('encoding', 'utf-8')
  662. return spawn(*args, **kwargs)