How to detect ESCape keypress in Python?
Solution 1:
Python 3 strings are unicode and, therefore, must be encoded to bytes for comparison. Try this test:
if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
aborted = True
break
Or this test:
if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
aborted = True
break
Or this test:
if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
aborted = True
break
Solution 2:
You don't need encode, decode, chr, ord, ....
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':
or if you'd like to see "27" in the code somewhere:
if msvcrt.kbhit() and msvcrt.getch()[0] == 27:
Solution 3:
You should really strip down more, like this one below:
>>> import msvcrt
>>> ch = msvcrt.getch()
# Press esc
>>> ch
b'\x1b'
>>> chr(27)
'\x1b'
>>> ch == chr(27)
False
So here is the problem: msvcrt.getch()
returns bytes
, chr(27)
returns string
. In Python 3 they are two distinct types, so the "==
" part will never work, and the if
statement will always be evaluated as False
.
The solution should be obvious to you.
More about strings vs bytes, from the book Dive into Python 3.
The interactive console is very useful for debugging, try use it more :)