Issue
This code works on Windows 10 but not on Linux. Linux does not seem to receive any keyboard events at all. When interrupting the program on Linux with Ctrl-C, this is the stack trace:
File "/home/andreas/src/magnetfeld-aux/keyboard_events.py", line 22, in <module>
key = kbd_q.get()
File "/usr/lib/python3.9/queue.py", line 171, in get
self.not_empty.wait()
File "/usr/lib/python3.9/threading.py", line 312, in wait
waiter.acquire()
KeyboardInterrupt
Here is the code:
from pynput import keyboard
from queue import Queue
kbd_q = Queue(maxsize=1)
def on_activate_s():
kbd_q.put("Hotkey s")
listener = keyboard.GlobalHotKeys({
's': on_activate_s,
})
listener.start()
while True:
key = kbd_q.get()
if key:
print(key)
How do I get this to run on Linux?
Solution
The thing that was missing was listener.wait()
, after starting the listener.
This works:
from pynput import keyboard
from queue import Queue
kbd_q = Queue(maxsize=1)
def on_activate_s():
kbd_q.put("Hotkey s")
listener = keyboard.GlobalHotKeys({
's': on_activate_s,
})
listener.start()
listener.wait()
while True:
key = kbd_q.get()
if key:
print(key)
Answered By - Andreas Schuldei Answer Checked By - Gilberto Lyons (WPSolving Admin)