tty.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Terminal utilities."""
  2. # Author: Steen Lumholt.
  3. from termios import *
  4. __all__ = ["cfmakeraw", "cfmakecbreak", "setraw", "setcbreak"]
  5. # Indices for termios list.
  6. IFLAG = 0
  7. OFLAG = 1
  8. CFLAG = 2
  9. LFLAG = 3
  10. ISPEED = 4
  11. OSPEED = 5
  12. CC = 6
  13. def cfmakeraw(mode):
  14. """Make termios mode raw."""
  15. # Clear all POSIX.1-2017 input mode flags.
  16. # See chapter 11 "General Terminal Interface"
  17. # of POSIX.1-2017 Base Definitions.
  18. mode[IFLAG] &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |
  19. INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF)
  20. # Do not post-process output.
  21. mode[OFLAG] &= ~OPOST
  22. # Disable parity generation and detection; clear character size mask;
  23. # let character size be 8 bits.
  24. mode[CFLAG] &= ~(PARENB | CSIZE)
  25. mode[CFLAG] |= CS8
  26. # Clear all POSIX.1-2017 local mode flags.
  27. mode[LFLAG] &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |
  28. IEXTEN | ISIG | NOFLSH | TOSTOP)
  29. # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,
  30. # Case B: MIN>0, TIME=0
  31. # A pending read shall block until MIN (here 1) bytes are received,
  32. # or a signal is received.
  33. mode[CC] = list(mode[CC])
  34. mode[CC][VMIN] = 1
  35. mode[CC][VTIME] = 0
  36. def cfmakecbreak(mode):
  37. """Make termios mode cbreak."""
  38. # Do not echo characters; disable canonical input.
  39. mode[LFLAG] &= ~(ECHO | ICANON)
  40. # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,
  41. # Case B: MIN>0, TIME=0
  42. # A pending read shall block until MIN (here 1) bytes are received,
  43. # or a signal is received.
  44. mode[CC] = list(mode[CC])
  45. mode[CC][VMIN] = 1
  46. mode[CC][VTIME] = 0
  47. def setraw(fd, when=TCSAFLUSH):
  48. """Put terminal into raw mode."""
  49. mode = tcgetattr(fd)
  50. new = list(mode)
  51. cfmakeraw(new)
  52. tcsetattr(fd, when, new)
  53. return mode
  54. def setcbreak(fd, when=TCSAFLUSH):
  55. """Put terminal into cbreak mode."""
  56. mode = tcgetattr(fd)
  57. new = list(mode)
  58. cfmakecbreak(new)
  59. tcsetattr(fd, when, new)
  60. return mode