Last active
August 31, 2024 18:18
-
-
Save razhangwei/7927b548cef8b58172064db55f2aefc0 to your computer and use it in GitHub Desktop.
pynput example #keyboard #macos #system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pynput import keyboard | |
from pynput.keyboard import Key, Controller | |
# For simulating keyboard presses | |
keyboard_controller = Controller() | |
def on_press(key): | |
try: | |
print(f'Alphanumeric key pressed: {key.char}') | |
except AttributeError: | |
print(f'Special key pressed: {key}') | |
# Simulate pressing and releasing a key | |
keyboard_controller.press(Key.esc) | |
keyboard_controller.release(Key.esc) | |
# Simulate typing a string | |
keyboard_controller.type('Hello, World!') | |
def on_release(key): | |
print(f'Key released: {key}') | |
if key == keyboard.Key.esc: | |
# Stop listener | |
return False | |
# Set up the listener | |
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: | |
listener.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment