>>> import msvcrt
>>> help(msvcrt.getch)
Help on built-in function getch in module msvcrt:
getch()
Read a keypress and return the resulting character as a byte string.
Nothing is echoed to the console. This call will block if a keypress is
not already available, but will not wait for Enter to be pressed. If the
pressed key was a special function key, this will return '\000' or
'\xe0'; the next call will return the keycode. The Control-C keypress
cannot be read with this function.
Can do a test,use
repr()
to see what really going on.
import msvcrt
while True:
character = msvcrt.getch()
print(repr(character))
if character == b'q':
break
So i get
b'\x00'
normal key and
b'\xe0'
for function keys.
Then can write it like this.
import msvcrt
import sys
while True:
ch = msvcrt.getch()
if ch in b'\x00':
ch = msvcrt.getch() # Second call returns the scan code
if ch in b'\xe0':
ch = msvcrt.getch() # Second call Function keys
if ch == b'q':
sys.exit()
else:
print(f'Key Pressed: {ch}')
Output:
E:\div_code
λ python scan.py
Key Pressed: b'h'
Key Pressed: b'e'
Key Pressed: b'l'
Key Pressed: b'l'
Key Pressed: b'o'
Key Pressed: b'\x1b
Key Pressed: b'\x1b
Key Pressed: b'\x1b
Key Pressed: b'\r'
Key Pressed: b'\r'
Key Pressed: b'\r'
3 times
Esc
and 3 times
Enter
after hello.
Key Scan Codes
So Esc(27) and Enter(13).
>>> k = b'\x1b'
>>> ord(k)
27
>>> k = b'\r'
>>> ord(k)
13
>>> if ord(b'\r') == 13:
... print('Enter key was pressed')
...
Enter key was pressed