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

836 lines
31 KiB

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