pty.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. """Pseudo terminal utilities."""
  2. # Bugs: No signal handling. Doesn't set slave termios and window size.
  3. # Only tested on Linux, FreeBSD, and macOS.
  4. # See: W. Richard Stevens. 1992. Advanced Programming in the
  5. # UNIX Environment. Chapter 19.
  6. # Author: Steen Lumholt -- with additions by Guido.
  7. from select import select
  8. import os
  9. import sys
  10. import tty
  11. # names imported directly for test mocking purposes
  12. from os import close, waitpid
  13. from tty import setraw, tcgetattr, tcsetattr
  14. __all__ = ["openpty", "fork", "spawn"]
  15. STDIN_FILENO = 0
  16. STDOUT_FILENO = 1
  17. STDERR_FILENO = 2
  18. CHILD = 0
  19. def openpty():
  20. """openpty() -> (master_fd, slave_fd)
  21. Open a pty master/slave pair, using os.openpty() if possible."""
  22. try:
  23. return os.openpty()
  24. except (AttributeError, OSError):
  25. pass
  26. master_fd, slave_name = _open_terminal()
  27. slave_fd = slave_open(slave_name)
  28. return master_fd, slave_fd
  29. def master_open():
  30. """master_open() -> (master_fd, slave_name)
  31. Open a pty master and return the fd, and the filename of the slave end.
  32. Deprecated, use openpty() instead."""
  33. import warnings
  34. warnings.warn("Use pty.openpty() instead.", DeprecationWarning, stacklevel=2) # Remove API in 3.14
  35. try:
  36. master_fd, slave_fd = os.openpty()
  37. except (AttributeError, OSError):
  38. pass
  39. else:
  40. slave_name = os.ttyname(slave_fd)
  41. os.close(slave_fd)
  42. return master_fd, slave_name
  43. return _open_terminal()
  44. def _open_terminal():
  45. """Open pty master and return (master_fd, tty_name)."""
  46. for x in 'pqrstuvwxyzPQRST':
  47. for y in '0123456789abcdef':
  48. pty_name = '/dev/pty' + x + y
  49. try:
  50. fd = os.open(pty_name, os.O_RDWR)
  51. except OSError:
  52. continue
  53. return (fd, '/dev/tty' + x + y)
  54. raise OSError('out of pty devices')
  55. def slave_open(tty_name):
  56. """slave_open(tty_name) -> slave_fd
  57. Open the pty slave and acquire the controlling terminal, returning
  58. opened filedescriptor.
  59. Deprecated, use openpty() instead."""
  60. import warnings
  61. warnings.warn("Use pty.openpty() instead.", DeprecationWarning, stacklevel=2) # Remove API in 3.14
  62. result = os.open(tty_name, os.O_RDWR)
  63. try:
  64. from fcntl import ioctl, I_PUSH
  65. except ImportError:
  66. return result
  67. try:
  68. ioctl(result, I_PUSH, "ptem")
  69. ioctl(result, I_PUSH, "ldterm")
  70. except OSError:
  71. pass
  72. return result
  73. def fork():
  74. """fork() -> (pid, master_fd)
  75. Fork and make the child a session leader with a controlling terminal."""
  76. try:
  77. pid, fd = os.forkpty()
  78. except (AttributeError, OSError):
  79. pass
  80. else:
  81. if pid == CHILD:
  82. try:
  83. os.setsid()
  84. except OSError:
  85. # os.forkpty() already set us session leader
  86. pass
  87. return pid, fd
  88. master_fd, slave_fd = openpty()
  89. pid = os.fork()
  90. if pid == CHILD:
  91. os.close(master_fd)
  92. os.login_tty(slave_fd)
  93. else:
  94. os.close(slave_fd)
  95. # Parent and child process.
  96. return pid, master_fd
  97. def _read(fd):
  98. """Default read function."""
  99. return os.read(fd, 1024)
  100. def _copy(master_fd, master_read=_read, stdin_read=_read):
  101. """Parent copy loop.
  102. Copies
  103. pty master -> standard output (master_read)
  104. standard input -> pty master (stdin_read)"""
  105. if os.get_blocking(master_fd):
  106. # If we write more than tty/ndisc is willing to buffer, we may block
  107. # indefinitely. So we set master_fd to non-blocking temporarily during
  108. # the copy operation.
  109. os.set_blocking(master_fd, False)
  110. try:
  111. _copy(master_fd, master_read=master_read, stdin_read=stdin_read)
  112. finally:
  113. # restore blocking mode for backwards compatibility
  114. os.set_blocking(master_fd, True)
  115. return
  116. high_waterlevel = 4096
  117. stdin_avail = master_fd != STDIN_FILENO
  118. stdout_avail = master_fd != STDOUT_FILENO
  119. i_buf = b''
  120. o_buf = b''
  121. while 1:
  122. rfds = []
  123. wfds = []
  124. if stdin_avail and len(i_buf) < high_waterlevel:
  125. rfds.append(STDIN_FILENO)
  126. if stdout_avail and len(o_buf) < high_waterlevel:
  127. rfds.append(master_fd)
  128. if stdout_avail and len(o_buf) > 0:
  129. wfds.append(STDOUT_FILENO)
  130. if len(i_buf) > 0:
  131. wfds.append(master_fd)
  132. rfds, wfds, _xfds = select(rfds, wfds, [])
  133. if STDOUT_FILENO in wfds:
  134. try:
  135. n = os.write(STDOUT_FILENO, o_buf)
  136. o_buf = o_buf[n:]
  137. except OSError:
  138. stdout_avail = False
  139. if master_fd in rfds:
  140. # Some OSes signal EOF by returning an empty byte string,
  141. # some throw OSErrors.
  142. try:
  143. data = master_read(master_fd)
  144. except OSError:
  145. data = b""
  146. if not data: # Reached EOF.
  147. return # Assume the child process has exited and is
  148. # unreachable, so we clean up.
  149. o_buf += data
  150. if master_fd in wfds:
  151. n = os.write(master_fd, i_buf)
  152. i_buf = i_buf[n:]
  153. if stdin_avail and STDIN_FILENO in rfds:
  154. data = stdin_read(STDIN_FILENO)
  155. if not data:
  156. stdin_avail = False
  157. else:
  158. i_buf += data
  159. def spawn(argv, master_read=_read, stdin_read=_read):
  160. """Create a spawned process."""
  161. if isinstance(argv, str):
  162. argv = (argv,)
  163. sys.audit('pty.spawn', argv)
  164. pid, master_fd = fork()
  165. if pid == CHILD:
  166. os.execlp(argv[0], *argv)
  167. try:
  168. mode = tcgetattr(STDIN_FILENO)
  169. setraw(STDIN_FILENO)
  170. restore = True
  171. except tty.error: # This is the same as termios.error
  172. restore = False
  173. try:
  174. _copy(master_fd, master_read, stdin_read)
  175. finally:
  176. if restore:
  177. tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
  178. close(master_fd)
  179. return waitpid(pid, 0)[1]