What key pressed? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: What key pressed? (/thread-11858.html) |
What key pressed? - ian - Jul-29-2018 I test the code below but not sure how to catch non-ASCII key, like Enter, Esc and so on. Thanks import msvcrt while True: if msvcrt.kbhit(): print(msvcrt.getch()) RE: What key pressed? - ichabod801 - Jul-29-2018 Try playing with this: import msvcrt while True: if msvcrt.kbhit(): print(repr(msvcrt.getch()))Some trial and error should get you the info you need. RE: What key pressed? - snippsat - Jul-29-2018 >>> 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': breakSo 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}') 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 |