Reputation: 126
I am trying to remap a shortcut combining pynput and pyautogui, but I am getting the error
in execute with keyboard.pressed(Key.shift): AttributeError: module 'pynput.keyboard' has no attribute 'pressed'
from pynput import keyboard
import pyautogui
# The key combination to check
COMBINATIONS = [
{keyboard.Key.ctrl, keyboard.KeyCode(char='z')},
{keyboard.Key.ctrl, keyboard.KeyCode(char='x')}
]
# The currently active modifiers
current = set()
def execute():
pyautogui.typewrite('Hello world!\n', interval=secs_between_keys)
#pyautogui.hotkey('cmd', 'v')
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
I am a total beginner and cannot figure out why I am not able to use pyautogui functions here. Would you kindly enlighten me? many many thanks!
Upvotes: 1
Views: 1290
Reputation: 8579
Here's a complete and tested example using pynput:
from pynput import keyboard
# The key combination to check
COMBINATIONS = [
{keyboard.Key.ctrl_l, keyboard.KeyCode(char='z')},
{keyboard.Key.ctrl_r, keyboard.KeyCode(char='z')},
{keyboard.Key.ctrl_l, keyboard.KeyCode(char='x')},
{keyboard.Key.ctrl_r, keyboard.KeyCode(char='x')}
]
# The currently active modifiers
current = set()
def execute():
print("Here I am")
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
The main problem seems to me related to use specific key combinations (e.g. Control + C) that are used by OS or other applications.
Upvotes: 1
Reputation: 2981
You want press
which takes the key
argument, instead of pressed
.
From the docs:-
Controller.press(key)
Presses a key.
A key may be either a string of length 1, one of the Key members or a KeyCode.
Upvotes: 1