/examples/keyecho.py

https://bitbucket.org/prologic/circuits/ · Python · 38 lines · 25 code · 12 blank · 1 comment · 4 complexity · ecf3bc3190dc93e1a115b6785ed688e9 MD5 · raw file

  1. #!/usr/bin/env python
  2. from circuits.io import File
  3. from circuits import Component
  4. import sys
  5. import tty
  6. import termios
  7. from contextlib import contextmanager
  8. @contextmanager
  9. def restore_tty_settings(fd):
  10. old = termios.tcgetattr(fd)
  11. yield
  12. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  13. class Echo(Component):
  14. def read(self, data):
  15. if data.lower() == "q":
  16. raise SystemExit, 0
  17. else:
  18. sys.stdout.write(data)
  19. sys.stdout.flush()
  20. def main():
  21. stdin = File("/dev/stdin", "r", bufsize=1)
  22. with restore_tty_settings(stdin._fd):
  23. tty.setraw(stdin._fd)
  24. (Echo() + stdin).run()
  25. if __name__ == '__main__':
  26. main()