Writting a CLI program, I would like to read Ctrl+<anything>
commands.
How can I listen and handle ie: Ctrl+R
combination keys from my CLI python application?
For the moment, it is necessary only for Linux environments. An pythonic approach would be the best option, but I don't know how.
From signals, it is possible to handle well-known inputs, but not custom keystrokes.
Pynput is a package that's setup to handle mouse and keyboard input for a variety of operating systems. This Github issue demonstrates how to detect held keys. If you don't want to follow the link:
from pynput import keyboard
# The key combination to check
COMBINATION = {keyboard.Key.cmd, keyboard.Key.ctrl}
# The currently active modifiers
current = set()
def on_press(key):
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION):
print('All modifiers active!')
if key == keyboard.Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.