magmax / python-readchar

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

readkey() doesn't work for arrow keys with unbuffered input #32

Closed eddawley closed 2 years ago

eddawley commented 6 years ago

Noticed this when debugging an issue with python-inquirer. readkey() will only return the first byte of arrow keys when stdin is unbuffered (either from PYTHON_UNBUFFERED or explicitly setting sys.stdin to unbuffered file object).

import binascii, readchar

while True:
    print '---%s---' % binascii.hexlify(readchar.readkey())

output (keypresses up, right, down, left):

[user@host ~]$ python foo.py 
---1b5b41---
---1b5b43---
---1b5b42---
---1b5b44---
Terminated
[user@host ~]$ python -u foo.py 
---1b1b---
---1b1b---
Terminated
IgorBonaP commented 6 years ago

Noticed a similar issue with other keys as well. Whenever I run readkey more than once in the same code it only gets the key in the first call. Example below.

-- test.py (pressing a, b, c, d on each run)

import readchar as rc
i=0
while i < 4:
    i+=1
    print("{0}# Press a key".format(i))
    key = rc.readkey()
    print("Key is {0}".format(key))

-- output

Key is a
2# Press a key
Key is None
3# Press a key
Key is None
4# Press a key
Key is None