test1.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import termios
  2. import tty
  3. import sys
  4. def interactive_read():
  5. """Reads characters one by one until 'q' is pressed, then restores terminal."""
  6. # 1. Get the file descriptor for standard input
  7. fd = sys.stdin.fileno()
  8. # 2. Get and make a COPY of the current terminal attributes
  9. # The termios functions operate on this list structure: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
  10. old_settings = termios.tcgetattr(fd)
  11. print("Terminal in default mode. Press Enter to continue to Cbreak mode...")
  12. sys.stdin.readline() # Read until Enter is pressed
  13. try:
  14. # 3. Enter Cbreak mode
  15. # tty.setcbreak is a helper that calls tcsetattr for you.
  16. # By default, tty.setcbreak uses termios.TCSAFLUSH!
  17. tty.setcbreak(fd, termios.TCSAFLUSH)
  18. print("Terminal now in Cbreak mode. Press 'q' to quit.")
  19. while True:
  20. # Read a single character immediately
  21. char = sys.stdin.read(1)
  22. if char == 'q':
  23. break
  24. print(f"You pressed: {repr(char)}") # repr shows things like '\n' for safety
  25. except Exception as e:
  26. print(f"An error occurred: {e}")
  27. finally:
  28. # 4. CRITICAL: Restore the original settings using TCSAFLUSH
  29. # We use TCSAFLUSH here to discard any half-typed input
  30. # that might have occurred while we were in cbreak mode.
  31. termios.tcsetattr(fd, termios.TCSAFLUSH, old_settings)
  32. print("\nTerminal settings restored. Goodbye!")
  33. if __name__ == "__main__":
  34. # The termios module only works on Unix-like systems.
  35. if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
  36. interactive_read()
  37. else:
  38. print("This script uses termios, which is only available on Unix-like systems.")