ptyprocess.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. import codecs
  2. import errno
  3. import fcntl
  4. import io
  5. import os
  6. import pty
  7. import resource
  8. import signal
  9. import struct
  10. import sys
  11. import termios
  12. import time
  13. try:
  14. import builtins # Python 3
  15. except ImportError:
  16. import __builtin__ as builtins # Python 2
  17. # Constants
  18. from pty import (STDIN_FILENO, CHILD)
  19. from .util import which
  20. _platform = sys.platform.lower()
  21. # Solaris uses internal __fork_pty(). All others use pty.fork().
  22. _is_solaris = (
  23. _platform.startswith('solaris') or
  24. _platform.startswith('sunos'))
  25. if _is_solaris:
  26. use_native_pty_fork = False
  27. from . import _fork_pty
  28. else:
  29. use_native_pty_fork = True
  30. PY3 = sys.version_info[0] >= 3
  31. if PY3:
  32. def _byte(i):
  33. return bytes([i])
  34. else:
  35. def _byte(i):
  36. return chr(i)
  37. class FileNotFoundError(OSError): pass
  38. class TimeoutError(OSError): pass
  39. _EOF, _INTR = None, None
  40. def _make_eof_intr():
  41. """Set constants _EOF and _INTR.
  42. This avoids doing potentially costly operations on module load.
  43. """
  44. global _EOF, _INTR
  45. if (_EOF is not None) and (_INTR is not None):
  46. return
  47. # inherit EOF and INTR definitions from controlling process.
  48. try:
  49. from termios import VEOF, VINTR
  50. try:
  51. fd = sys.__stdin__.fileno()
  52. except ValueError:
  53. # ValueError: I/O operation on closed file
  54. fd = sys.__stdout__.fileno()
  55. intr = ord(termios.tcgetattr(fd)[6][VINTR])
  56. eof = ord(termios.tcgetattr(fd)[6][VEOF])
  57. except (ImportError, OSError, IOError, ValueError, termios.error):
  58. # unless the controlling process is also not a terminal,
  59. # such as cron(1), or when stdin and stdout are both closed.
  60. # Fall-back to using CEOF and CINTR. There
  61. try:
  62. from termios import CEOF, CINTR
  63. (intr, eof) = (CINTR, CEOF)
  64. except ImportError:
  65. # ^C, ^D
  66. (intr, eof) = (3, 4)
  67. _INTR = _byte(intr)
  68. _EOF = _byte(eof)
  69. class PtyProcessError(Exception):
  70. """Generic error class for this package."""
  71. # setecho and setwinsize are pulled out here because on some platforms, we need
  72. # to do this from the child before we exec()
  73. def _setecho(fd, state):
  74. errmsg = 'setecho() may not be called on this platform'
  75. try:
  76. attr = termios.tcgetattr(fd)
  77. except termios.error as err:
  78. if err.args[0] == errno.EINVAL:
  79. raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
  80. raise
  81. if state:
  82. attr[3] = attr[3] | termios.ECHO
  83. else:
  84. attr[3] = attr[3] & ~termios.ECHO
  85. try:
  86. # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
  87. # blocked on some platforms. TCSADRAIN would probably be ideal.
  88. termios.tcsetattr(fd, termios.TCSANOW, attr)
  89. except IOError as err:
  90. if err.args[0] == errno.EINVAL:
  91. raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
  92. raise
  93. def _setwinsize(fd, rows, cols):
  94. # Some very old platforms have a bug that causes the value for
  95. # termios.TIOCSWINSZ to be truncated. There was a hack here to work
  96. # around this, but it caused problems with newer platforms so has been
  97. # removed. For details see https://github.com/pexpect/pexpect/issues/39
  98. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
  99. # Note, assume ws_xpixel and ws_ypixel are zero.
  100. s = struct.pack('HHHH', rows, cols, 0, 0)
  101. fcntl.ioctl(fd, TIOCSWINSZ, s)
  102. class PtyProcess(object):
  103. '''This class represents a process running in a pseudoterminal.
  104. The main constructor is the :meth:`spawn` classmethod.
  105. '''
  106. string_type = bytes
  107. if PY3:
  108. linesep = os.linesep.encode('ascii')
  109. crlf = '\r\n'.encode('ascii')
  110. @staticmethod
  111. def write_to_stdout(b):
  112. try:
  113. return sys.stdout.buffer.write(b)
  114. except AttributeError:
  115. # If stdout has been replaced, it may not have .buffer
  116. return sys.stdout.write(b.decode('ascii', 'replace'))
  117. else:
  118. linesep = os.linesep
  119. crlf = '\r\n'
  120. write_to_stdout = sys.stdout.write
  121. encoding = None
  122. argv = None
  123. env = None
  124. launch_dir = None
  125. def __init__(self, pid, fd):
  126. _make_eof_intr() # Ensure _EOF and _INTR are calculated
  127. self.pid = pid
  128. self.fd = fd
  129. readf = io.open(fd, 'rb', buffering=0)
  130. writef = io.open(fd, 'wb', buffering=0, closefd=False)
  131. self.fileobj = io.BufferedRWPair(readf, writef)
  132. self.terminated = False
  133. self.closed = False
  134. self.exitstatus = None
  135. self.signalstatus = None
  136. # status returned by os.waitpid
  137. self.status = None
  138. self.flag_eof = False
  139. # Used by close() to give kernel time to update process status.
  140. # Time in seconds.
  141. self.delayafterclose = 0.1
  142. # Used by terminate() to give kernel time to update process status.
  143. # Time in seconds.
  144. self.delayafterterminate = 0.1
  145. @classmethod
  146. def spawn(
  147. cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
  148. dimensions=(24, 80)):
  149. '''Start the given command in a child process in a pseudo terminal.
  150. This does all the fork/exec type of stuff for a pty, and returns an
  151. instance of PtyProcess.
  152. If preexec_fn is supplied, it will be called with no arguments in the
  153. child process before exec-ing the specified command.
  154. It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
  155. Dimensions of the psuedoterminal used for the subprocess can be
  156. specified as a tuple (rows, cols), or the default (24, 80) will be used.
  157. '''
  158. # Note that it is difficult for this method to fail.
  159. # You cannot detect if the child process cannot start.
  160. # So the only way you can tell if the child process started
  161. # or not is to try to read from the file descriptor. If you get
  162. # EOF immediately then it means that the child is already dead.
  163. # That may not necessarily be bad because you may have spawned a child
  164. # that performs some task; creates no stdout output; and then dies.
  165. if not isinstance(argv, (list, tuple)):
  166. raise TypeError("Expected a list or tuple for argv, got %r" % argv)
  167. # Shallow copy of argv so we can modify it
  168. argv = argv[:]
  169. command = argv[0]
  170. command_with_path = which(command)
  171. if command_with_path is None:
  172. raise FileNotFoundError('The command was not found or was not ' +
  173. 'executable: %s.' % command)
  174. command = command_with_path
  175. argv[0] = command
  176. # [issue #119] To prevent the case where exec fails and the user is
  177. # stuck interacting with a python child process instead of whatever
  178. # was expected, we implement the solution from
  179. # http://stackoverflow.com/a/3703179 to pass the exception to the
  180. # parent process
  181. # [issue #119] 1. Before forking, open a pipe in the parent process.
  182. exec_err_pipe_read, exec_err_pipe_write = os.pipe()
  183. if use_native_pty_fork:
  184. pid, fd = pty.fork()
  185. else:
  186. # Use internal fork_pty, for Solaris
  187. pid, fd = _fork_pty.fork_pty()
  188. # Some platforms must call setwinsize() and setecho() from the
  189. # child process, and others from the master process. We do both,
  190. # allowing IOError for either.
  191. if pid == CHILD:
  192. # set window size
  193. try:
  194. _setwinsize(STDIN_FILENO, *dimensions)
  195. except IOError as err:
  196. if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
  197. raise
  198. # disable echo if spawn argument echo was unset
  199. if not echo:
  200. try:
  201. _setecho(STDIN_FILENO, False)
  202. except (IOError, termios.error) as err:
  203. if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
  204. raise
  205. # [issue #119] 3. The child closes the reading end and sets the
  206. # close-on-exec flag for the writing end.
  207. os.close(exec_err_pipe_read)
  208. fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
  209. # Do not allow child to inherit open file descriptors from parent,
  210. # with the exception of the exec_err_pipe_write of the pipe
  211. max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
  212. os.closerange(3, exec_err_pipe_write)
  213. os.closerange(exec_err_pipe_write+1, max_fd)
  214. if cwd is not None:
  215. os.chdir(cwd)
  216. if preexec_fn is not None:
  217. try:
  218. preexec_fn()
  219. except Exception as e:
  220. ename = type(e).__name__
  221. tosend = '{}:0:{}'.format(ename, str(e))
  222. if PY3:
  223. tosend = tosend.encode('utf-8')
  224. os.write(exec_err_pipe_write, tosend)
  225. os.close(exec_err_pipe_write)
  226. os._exit(1)
  227. try:
  228. if env is None:
  229. os.execv(command, argv)
  230. else:
  231. os.execvpe(command, argv, env)
  232. except OSError as err:
  233. # [issue #119] 5. If exec fails, the child writes the error
  234. # code back to the parent using the pipe, then exits.
  235. tosend = 'OSError:{}:{}'.format(err.errno, str(err))
  236. if PY3:
  237. tosend = tosend.encode('utf-8')
  238. os.write(exec_err_pipe_write, tosend)
  239. os.close(exec_err_pipe_write)
  240. os._exit(os.EX_OSERR)
  241. # Parent
  242. inst = cls(pid, fd)
  243. # Set some informational attributes
  244. inst.argv = argv
  245. if env is not None:
  246. inst.env = env
  247. if cwd is not None:
  248. inst.launch_dir = cwd
  249. # [issue #119] 2. After forking, the parent closes the writing end
  250. # of the pipe and reads from the reading end.
  251. os.close(exec_err_pipe_write)
  252. exec_err_data = os.read(exec_err_pipe_read, 4096)
  253. os.close(exec_err_pipe_read)
  254. # [issue #119] 6. The parent reads eof (a zero-length read) if the
  255. # child successfully performed exec, since close-on-exec made
  256. # successful exec close the writing end of the pipe. Or, if exec
  257. # failed, the parent reads the error code and can proceed
  258. # accordingly. Either way, the parent blocks until the child calls
  259. # exec.
  260. if len(exec_err_data) != 0:
  261. try:
  262. errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
  263. exctype = getattr(builtins, errclass.decode('ascii'), Exception)
  264. exception = exctype(errmsg.decode('utf-8', 'replace'))
  265. if exctype is OSError:
  266. exception.errno = int(errno_s)
  267. except:
  268. raise Exception('Subprocess failed, got bad error data: %r'
  269. % exec_err_data)
  270. else:
  271. raise exception
  272. try:
  273. inst.setwinsize(*dimensions)
  274. except IOError as err:
  275. if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
  276. raise
  277. return inst
  278. def __repr__(self):
  279. clsname = type(self).__name__
  280. if self.argv is not None:
  281. args = [repr(self.argv)]
  282. if self.env is not None:
  283. args.append("env=%r" % self.env)
  284. if self.launch_dir is not None:
  285. args.append("cwd=%r" % self.launch_dir)
  286. return "{}.spawn({})".format(clsname, ", ".join(args))
  287. else:
  288. return "{}(pid={}, fd={})".format(clsname, self.pid, self.fd)
  289. @staticmethod
  290. def _coerce_send_string(s):
  291. if not isinstance(s, bytes):
  292. return s.encode('utf-8')
  293. return s
  294. @staticmethod
  295. def _coerce_read_string(s):
  296. return s
  297. def __del__(self):
  298. '''This makes sure that no system resources are left open. Python only
  299. garbage collects Python objects. OS file descriptors are not Python
  300. objects, so they must be handled explicitly. If the child file
  301. descriptor was opened outside of this class (passed to the constructor)
  302. then this does not close it. '''
  303. if not self.closed:
  304. # It is possible for __del__ methods to execute during the
  305. # teardown of the Python VM itself. Thus self.close() may
  306. # trigger an exception because os.close may be None.
  307. try:
  308. self.close()
  309. # which exception, shouldn't we catch explicitly .. ?
  310. except:
  311. pass
  312. def fileno(self):
  313. '''This returns the file descriptor of the pty for the child.
  314. '''
  315. return self.fd
  316. def close(self, force=True):
  317. '''This closes the connection with the child application. Note that
  318. calling close() more than once is valid. This emulates standard Python
  319. behavior with files. Set force to True if you want to make sure that
  320. the child is terminated (SIGKILL is sent if the child ignores SIGHUP
  321. and SIGINT). '''
  322. if not self.closed:
  323. self.flush()
  324. self.fileobj.close() # Closes the file descriptor
  325. # Give kernel time to update process status.
  326. time.sleep(self.delayafterclose)
  327. if self.isalive():
  328. if not self.terminate(force):
  329. raise PtyProcessError('Could not terminate the child.')
  330. self.fd = -1
  331. self.closed = True
  332. #self.pid = None
  333. def flush(self):
  334. '''This does nothing. It is here to support the interface for a
  335. File-like object. '''
  336. pass
  337. def isatty(self):
  338. '''This returns True if the file descriptor is open and connected to a
  339. tty(-like) device, else False.
  340. On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
  341. the child pty may not appear as a terminal device. This means
  342. methods such as setecho(), setwinsize(), getwinsize() may raise an
  343. IOError. '''
  344. return os.isatty(self.fd)
  345. def waitnoecho(self, timeout=None):
  346. '''This waits until the terminal ECHO flag is set False. This returns
  347. True if the echo mode is off. This returns False if the ECHO flag was
  348. not set False before the timeout. This can be used to detect when the
  349. child is waiting for a password. Usually a child application will turn
  350. off echo mode when it is waiting for the user to enter a password. For
  351. example, instead of expecting the "password:" prompt you can wait for
  352. the child to set ECHO off::
  353. p = pexpect.spawn('ssh user@example.com')
  354. p.waitnoecho()
  355. p.sendline(mypassword)
  356. If timeout==None then this method to block until ECHO flag is False.
  357. '''
  358. if timeout is not None:
  359. end_time = time.time() + timeout
  360. while True:
  361. if not self.getecho():
  362. return True
  363. if timeout < 0 and timeout is not None:
  364. return False
  365. if timeout is not None:
  366. timeout = end_time - time.time()
  367. time.sleep(0.1)
  368. def getecho(self):
  369. '''This returns the terminal echo mode. This returns True if echo is
  370. on or False if echo is off. Child applications that are expecting you
  371. to enter a password often set ECHO False. See waitnoecho().
  372. Not supported on platforms where ``isatty()`` returns False. '''
  373. try:
  374. attr = termios.tcgetattr(self.fd)
  375. except termios.error as err:
  376. errmsg = 'getecho() may not be called on this platform'
  377. if err.args[0] == errno.EINVAL:
  378. raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
  379. raise
  380. self.echo = bool(attr[3] & termios.ECHO)
  381. return self.echo
  382. def setecho(self, state):
  383. '''This sets the terminal echo mode on or off. Note that anything the
  384. child sent before the echo will be lost, so you should be sure that
  385. your input buffer is empty before you call setecho(). For example, the
  386. following will work as expected::
  387. p = pexpect.spawn('cat') # Echo is on by default.
  388. p.sendline('1234') # We expect see this twice from the child...
  389. p.expect(['1234']) # ... once from the tty echo...
  390. p.expect(['1234']) # ... and again from cat itself.
  391. p.setecho(False) # Turn off tty echo
  392. p.sendline('abcd') # We will set this only once (echoed by cat).
  393. p.sendline('wxyz') # We will set this only once (echoed by cat)
  394. p.expect(['abcd'])
  395. p.expect(['wxyz'])
  396. The following WILL NOT WORK because the lines sent before the setecho
  397. will be lost::
  398. p = pexpect.spawn('cat')
  399. p.sendline('1234')
  400. p.setecho(False) # Turn off tty echo
  401. p.sendline('abcd') # We will set this only once (echoed by cat).
  402. p.sendline('wxyz') # We will set this only once (echoed by cat)
  403. p.expect(['1234'])
  404. p.expect(['1234'])
  405. p.expect(['abcd'])
  406. p.expect(['wxyz'])
  407. Not supported on platforms where ``isatty()`` returns False.
  408. '''
  409. _setecho(self.fd, state)
  410. self.echo = state
  411. def read(self, size=1024):
  412. """Read and return at most ``size`` bytes from the pty.
  413. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  414. terminal was closed.
  415. Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
  416. with the vagaries of EOF on platforms that do strange things, like IRIX
  417. or older Solaris systems. It handles the errno=EIO pattern used on
  418. Linux, and the empty-string return used on BSD platforms and (seemingly)
  419. on recent Solaris.
  420. """
  421. try:
  422. s = self.fileobj.read1(size)
  423. except (OSError, IOError) as err:
  424. if err.args[0] == errno.EIO:
  425. # Linux-style EOF
  426. self.flag_eof = True
  427. raise EOFError('End Of File (EOF). Exception style platform.')
  428. raise
  429. if s == b'':
  430. # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
  431. self.flag_eof = True
  432. raise EOFError('End Of File (EOF). Empty string style platform.')
  433. return s
  434. def readline(self):
  435. """Read one line from the pseudoterminal, and return it as unicode.
  436. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  437. terminal was closed.
  438. """
  439. try:
  440. s = self.fileobj.readline()
  441. except (OSError, IOError) as err:
  442. if err.args[0] == errno.EIO:
  443. # Linux-style EOF
  444. self.flag_eof = True
  445. raise EOFError('End Of File (EOF). Exception style platform.')
  446. raise
  447. if s == b'':
  448. # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
  449. self.flag_eof = True
  450. raise EOFError('End Of File (EOF). Empty string style platform.')
  451. return s
  452. def _writeb(self, b, flush=True):
  453. n = self.fileobj.write(b)
  454. if flush:
  455. self.fileobj.flush()
  456. return n
  457. def write(self, s, flush=True):
  458. """Write bytes to the pseudoterminal.
  459. Returns the number of bytes written.
  460. """
  461. return self._writeb(s, flush=flush)
  462. def sendcontrol(self, char):
  463. '''Helper method that wraps send() with mnemonic access for sending control
  464. character to the child (such as Ctrl-C or Ctrl-D). For example, to send
  465. Ctrl-G (ASCII 7, bell, '\a')::
  466. child.sendcontrol('g')
  467. See also, sendintr() and sendeof().
  468. '''
  469. char = char.lower()
  470. a = ord(char)
  471. if 97 <= a <= 122:
  472. a = a - ord('a') + 1
  473. byte = _byte(a)
  474. return self._writeb(byte), byte
  475. d = {'@': 0, '`': 0,
  476. '[': 27, '{': 27,
  477. '\\': 28, '|': 28,
  478. ']': 29, '}': 29,
  479. '^': 30, '~': 30,
  480. '_': 31,
  481. '?': 127}
  482. if char not in d:
  483. return 0, b''
  484. byte = _byte(d[char])
  485. return self._writeb(byte), byte
  486. def sendeof(self):
  487. '''This sends an EOF to the child. This sends a character which causes
  488. the pending parent output buffer to be sent to the waiting child
  489. program without waiting for end-of-line. If it is the first character
  490. of the line, the read() in the user program returns 0, which signifies
  491. end-of-file. This means to work as expected a sendeof() has to be
  492. called at the beginning of a line. This method does not send a newline.
  493. It is the responsibility of the caller to ensure the eof is sent at the
  494. beginning of a line. '''
  495. return self._writeb(_EOF), _EOF
  496. def sendintr(self):
  497. '''This sends a SIGINT to the child. It does not require
  498. the SIGINT to be the first character on a line. '''
  499. return self._writeb(_INTR), _INTR
  500. def eof(self):
  501. '''This returns True if the EOF exception was ever raised.
  502. '''
  503. return self.flag_eof
  504. def terminate(self, force=False):
  505. '''This forces a child process to terminate. It starts nicely with
  506. SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
  507. returns True if the child was terminated. This returns False if the
  508. child could not be terminated. '''
  509. if not self.isalive():
  510. return True
  511. try:
  512. self.kill(signal.SIGHUP)
  513. time.sleep(self.delayafterterminate)
  514. if not self.isalive():
  515. return True
  516. self.kill(signal.SIGCONT)
  517. time.sleep(self.delayafterterminate)
  518. if not self.isalive():
  519. return True
  520. self.kill(signal.SIGINT)
  521. time.sleep(self.delayafterterminate)
  522. if not self.isalive():
  523. return True
  524. if force:
  525. self.kill(signal.SIGKILL)
  526. time.sleep(self.delayafterterminate)
  527. if not self.isalive():
  528. return True
  529. else:
  530. return False
  531. return False
  532. except OSError:
  533. # I think there are kernel timing issues that sometimes cause
  534. # this to happen. I think isalive() reports True, but the
  535. # process is dead to the kernel.
  536. # Make one last attempt to see if the kernel is up to date.
  537. time.sleep(self.delayafterterminate)
  538. if not self.isalive():
  539. return True
  540. else:
  541. return False
  542. def wait(self):
  543. '''This waits until the child exits. This is a blocking call. This will
  544. not read any data from the child, so this will block forever if the
  545. child has unread output and has terminated. In other words, the child
  546. may have printed output then called exit(), but, the child is
  547. technically still alive until its output is read by the parent. '''
  548. if self.isalive():
  549. pid, status = os.waitpid(self.pid, 0)
  550. else:
  551. return self.exitstatus
  552. self.exitstatus = os.WEXITSTATUS(status)
  553. if os.WIFEXITED(status):
  554. self.status = status
  555. self.exitstatus = os.WEXITSTATUS(status)
  556. self.signalstatus = None
  557. self.terminated = True
  558. elif os.WIFSIGNALED(status):
  559. self.status = status
  560. self.exitstatus = None
  561. self.signalstatus = os.WTERMSIG(status)
  562. self.terminated = True
  563. elif os.WIFSTOPPED(status): # pragma: no cover
  564. # You can't call wait() on a child process in the stopped state.
  565. raise PtyProcessError('Called wait() on a stopped child ' +
  566. 'process. This is not supported. Is some other ' +
  567. 'process attempting job control with our child pid?')
  568. return self.exitstatus
  569. def isalive(self):
  570. '''This tests if the child process is running or not. This is
  571. non-blocking. If the child was terminated then this will read the
  572. exitstatus or signalstatus of the child. This returns True if the child
  573. process appears to be running or False if not. It can take literally
  574. SECONDS for Solaris to return the right status. '''
  575. if self.terminated:
  576. return False
  577. if self.flag_eof:
  578. # This is for Linux, which requires the blocking form
  579. # of waitpid to get the status of a defunct process.
  580. # This is super-lame. The flag_eof would have been set
  581. # in read_nonblocking(), so this should be safe.
  582. waitpid_options = 0
  583. else:
  584. waitpid_options = os.WNOHANG
  585. try:
  586. pid, status = os.waitpid(self.pid, waitpid_options)
  587. except OSError as e:
  588. # No child processes
  589. if e.errno == errno.ECHILD:
  590. raise PtyProcessError('isalive() encountered condition ' +
  591. 'where "terminated" is 0, but there was no child ' +
  592. 'process. Did someone else call waitpid() ' +
  593. 'on our process?')
  594. else:
  595. raise
  596. # I have to do this twice for Solaris.
  597. # I can't even believe that I figured this out...
  598. # If waitpid() returns 0 it means that no child process
  599. # wishes to report, and the value of status is undefined.
  600. if pid == 0:
  601. try:
  602. ### os.WNOHANG) # Solaris!
  603. pid, status = os.waitpid(self.pid, waitpid_options)
  604. except OSError as e: # pragma: no cover
  605. # This should never happen...
  606. if e.errno == errno.ECHILD:
  607. raise PtyProcessError('isalive() encountered condition ' +
  608. 'that should never happen. There was no child ' +
  609. 'process. Did someone else call waitpid() ' +
  610. 'on our process?')
  611. else:
  612. raise
  613. # If pid is still 0 after two calls to waitpid() then the process
  614. # really is alive. This seems to work on all platforms, except for
  615. # Irix which seems to require a blocking call on waitpid or select,
  616. # so I let read_nonblocking take care of this situation
  617. # (unfortunately, this requires waiting through the timeout).
  618. if pid == 0:
  619. return True
  620. if pid == 0:
  621. return True
  622. if os.WIFEXITED(status):
  623. self.status = status
  624. self.exitstatus = os.WEXITSTATUS(status)
  625. self.signalstatus = None
  626. self.terminated = True
  627. elif os.WIFSIGNALED(status):
  628. self.status = status
  629. self.exitstatus = None
  630. self.signalstatus = os.WTERMSIG(status)
  631. self.terminated = True
  632. elif os.WIFSTOPPED(status):
  633. raise PtyProcessError('isalive() encountered condition ' +
  634. 'where child process is stopped. This is not ' +
  635. 'supported. Is some other process attempting ' +
  636. 'job control with our child pid?')
  637. return False
  638. def kill(self, sig):
  639. """Send the given signal to the child application.
  640. In keeping with UNIX tradition it has a misleading name. It does not
  641. necessarily kill the child unless you send the right signal. See the
  642. :mod:`signal` module for constants representing signal numbers.
  643. """
  644. # Same as os.kill, but the pid is given for you.
  645. if self.isalive():
  646. os.kill(self.pid, sig)
  647. def getwinsize(self):
  648. """Return the window size of the pseudoterminal as a tuple (rows, cols).
  649. """
  650. TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
  651. s = struct.pack('HHHH', 0, 0, 0, 0)
  652. x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
  653. return struct.unpack('HHHH', x)[0:2]
  654. def setwinsize(self, rows, cols):
  655. """Set the terminal window size of the child tty.
  656. This will cause a SIGWINCH signal to be sent to the child. This does not
  657. change the physical window size. It changes the size reported to
  658. TTY-aware applications like vi or curses -- applications that respond to
  659. the SIGWINCH signal.
  660. """
  661. return _setwinsize(self.fd, rows, cols)
  662. class PtyProcessUnicode(PtyProcess):
  663. """Unicode wrapper around a process running in a pseudoterminal.
  664. This class exposes a similar interface to :class:`PtyProcess`, but its read
  665. methods return unicode, and its :meth:`write` accepts unicode.
  666. """
  667. if PY3:
  668. string_type = str
  669. else:
  670. string_type = unicode # analysis:ignore
  671. def __init__(self, pid, fd, encoding='utf-8', codec_errors='strict'):
  672. super(PtyProcessUnicode, self).__init__(pid, fd)
  673. self.encoding = encoding
  674. self.codec_errors = codec_errors
  675. self.decoder = codecs.getincrementaldecoder(encoding)(errors=codec_errors)
  676. def read(self, size=1024):
  677. """Read at most ``size`` bytes from the pty, return them as unicode.
  678. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  679. terminal was closed.
  680. The size argument still refers to bytes, not unicode code points.
  681. """
  682. b = super(PtyProcessUnicode, self).read(size)
  683. return self.decoder.decode(b, final=False)
  684. def readline(self):
  685. """Read one line from the pseudoterminal, and return it as unicode.
  686. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  687. terminal was closed.
  688. """
  689. b = super(PtyProcessUnicode, self).readline()
  690. return self.decoder.decode(b, final=False)
  691. def write(self, s):
  692. """Write the unicode string ``s`` to the pseudoterminal.
  693. Returns the number of bytes written.
  694. """
  695. b = s.encode(self.encoding)
  696. return super(PtyProcessUnicode, self).write(b)