I'm writing a simple Python 3 script and I want to be able to intercept key presses inside the terminal window in order to do something depending on the returned value, for example.
I also want a cross-platform solution.
I would like to reproduce something like this:
import msvcrt
key = ord(msvcrt.getch()) # Wait for a key to be pressed.
if key == 27: # The ESC key
print("You have pressed the ESC key!")
But msvcrt
is a Windows-specific module according to the Python docs (and my tests):
These functions provide access to some useful capabilities on Windows platforms.
I've found the keyboard
module which is quite simple to use (and more cross-platform) but I didn't manage to "catch" only the keys pressed inside the terminal window.
For example:
import keyboard as kb
key = kb.read_hotkey()
if key == "esc": # The ESC key
print("You have pressed the ESC key!")
The code given above intercepts key presses not only when the terminal window where the script is executed is focused, but also when it is not.
So, to conclude, do you know a pythonic way to intercept key presses inside the terminal window (and not outside) where the script is executed (something like an input()
without having to press Enter), and which is cross-platform (at least compatible with GNU/Linux and Windows)?
Thank you in advance for your answers,
Regards,
Alexis.