I'm writing a very simple piece of code.
- I want to listen to the keyboard.
- When I press F11, the message "Activated..." must be displayed, just once.
- When I press F11 again, the message "Deactivated..." must be displayed, also just once.
- And so on...
- When I press F12, I want the listener to stop.
Here's my piece of code and I'm having troubles to find the right implementation to avoid the constant loop ("Activated... Deactivated... Activated... Deactivated...") when I press F11.
Also, any advice to have a better implementation, more state-of-the-art, more pythonic, is welcome!
# -*- coding: utf-8 -*-
from pynput import keyboard
is_active = False
def on_press(key):
global is_active
# Activate/Deactivate when pressing F11
if key == keyboard.Key.f11:
if is_active:
is_active = False
print("Deactivate...")
else:
is_active = True
print("Activate...")
# Stop "on_press" listener
if key == keyboard.Key.f12:
return False
with keyboard.Listener(on_press=on_press) as listener:
listener.join()