magmax / python-readchar

Python library to read characters and key strokes
MIT License
143 stars 45 forks source link

Sometimes special characters appear ^[[ #48

Closed prem111as closed 2 years ago

prem111as commented 4 years ago

During continuous pressing of up or down Sometimes special characters appear ^ [[

rogerdahl commented 4 years ago

That's because the library only turns on raw mode, which hides character input, while inside the readchar() method. Any time you push a key when the program is doing something else, the terminal will echo the escape codes back. You can work around that by turning off echoing the whole time your program is running. E.g., like this example in the Python termios docs.

import termios, sys

...

if __name__ == '__main__':
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        sys.exit(main())
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)