pty.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """Pseudo terminal utilities."""
  2. # Bugs: No signal handling. Doesn't set slave termios and window size.
  3. # Only tested on Linux.
  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. __all__ = ["openpty","fork","spawn"]
  12. STDIN_FILENO = 0
  13. STDOUT_FILENO = 1
  14. STDERR_FILENO = 2
  15. CHILD = 0
  16. def openpty():
  17. """openpty() -> (master_fd, slave_fd)
  18. Open a pty master/slave pair, using os.openpty() if possible."""
  19. try:
  20. return os.openpty()
  21. except (AttributeError, OSError):
  22. pass
  23. master_fd, slave_name = _open_terminal()
  24. slave_fd = slave_open(slave_name)
  25. return master_fd, slave_fd
  26. def master_open():
  27. """master_open() -> (master_fd, slave_name)
  28. Open a pty master and return the fd, and the filename of the slave end.
  29. Deprecated, use openpty() instead."""
  30. try:
  31. master_fd, slave_fd = os.openpty()
  32. except (AttributeError, OSError):
  33. pass
  34. else:
  35. slave_name = os.ttyname(slave_fd)
  36. os.close(slave_fd)
  37. return master_fd, slave_name
  38. return _open_terminal()
  39. def _open_terminal():
  40. """Open pty master and return (master_fd, tty_name)."""
  41. for x in 'pqrstuvwxyzPQRST':
  42. for y in '0123456789abcdef':
  43. pty_name = '/dev/pty' + x + y
  44. try:
  45. fd = os.open(pty_name, os.O_RDWR)
  46. except OSError:
  47. continue
  48. return (fd, '/dev/tty' + x + y)
  49. raise OSError('out of pty devices')
  50. def slave_open(tty_name):
  51. """slave_open(tty_name) -> slave_fd
  52. Open the pty slave and acquire the controlling terminal, returning
  53. opened filedescriptor.
  54. Deprecated, use openpty() instead."""
  55. result = os.open(tty_name, os.O_RDWR)
  56. try:
  57. from fcntl import ioctl, I_PUSH
  58. except ImportError:
  59. return result
  60. try:
  61. ioctl(result, I_PUSH, "ptem")
  62. ioctl(result, I_PUSH, "ldterm")
  63. except OSError:
  64. pass
  65. return result
  66. def fork():
  67. """fork() -> (pid, master_fd)
  68. Fork and make the child a session leader with a controlling terminal."""
  69. try:
  70. pid, fd = os.forkpty()
  71. except (AttributeError, OSError):
  72. pass
  73. else:
  74. if pid == CHILD:
  75. try:
  76. os.setsid()
  77. except OSError:
  78. # os.forkpty() already set us session leader
  79. pass
  80. return pid, fd
  81. master_fd, slave_fd = openpty()
  82. pid = os.fork()
  83. if pid == CHILD:
  84. # Establish a new session.
  85. os.setsid()
  86. os.close(master_fd)
  87. # Slave becomes stdin/stdout/stderr of child.
  88. os.dup2(slave_fd, STDIN_FILENO)
  89. os.dup2(slave_fd, STDOUT_FILENO)
  90. os.dup2(slave_fd, STDERR_FILENO)
  91. if (slave_fd > STDERR_FILENO):
  92. os.close (slave_fd)
  93. # Explicitly open the tty to make it become a controlling tty.
  94. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
  95. os.close(tmp_fd)
  96. else:
  97. os.close(slave_fd)
  98. # Parent and child process.
  99. return pid, master_fd
  100. def _writen(fd, data):
  101. """Write all the data to a descriptor."""
  102. while data:
  103. n = os.write(fd, data)
  104. data = data[n:]
  105. def _read(fd):
  106. """Default read function."""
  107. return os.read(fd, 1024)
  108. def _copy(master_fd, master_read=_read, stdin_read=_read):
  109. """Parent copy loop.
  110. Copies
  111. pty master -> standard output (master_read)
  112. standard input -> pty master (stdin_read)"""
  113. fds = [master_fd, STDIN_FILENO]
  114. while True:
  115. rfds, wfds, xfds = select(fds, [], [])
  116. if master_fd in rfds:
  117. data = master_read(master_fd)
  118. if not data: # Reached EOF.
  119. fds.remove(master_fd)
  120. else:
  121. os.write(STDOUT_FILENO, data)
  122. if STDIN_FILENO in rfds:
  123. data = stdin_read(STDIN_FILENO)
  124. if not data:
  125. fds.remove(STDIN_FILENO)
  126. else:
  127. _writen(master_fd, data)
  128. def spawn(argv, master_read=_read, stdin_read=_read):
  129. """Create a spawned process."""
  130. if type(argv) == type(''):
  131. argv = (argv,)
  132. sys.audit('pty.spawn', argv)
  133. pid, master_fd = fork()
  134. if pid == CHILD:
  135. os.execlp(argv[0], *argv)
  136. try:
  137. mode = tty.tcgetattr(STDIN_FILENO)
  138. tty.setraw(STDIN_FILENO)
  139. restore = 1
  140. except tty.error: # This is the same as termios.error
  141. restore = 0
  142. try:
  143. _copy(master_fd, master_read, stdin_read)
  144. except OSError:
  145. if restore:
  146. tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
  147. os.close(master_fd)
  148. return os.waitpid(pid, 0)[1]