ptyprocess.py 31 KB

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