When I hold down the key on the physical keyboard several times a signal is triggered to the chosen key, at least that’s how events in most Apis working with "input" respond back, for example, in Javascript when placing events document.onkeydown = e => console.log(e.key);
or document.onkeypress = e => console.log(e.key);
to hear the keys will be fired several console.log
, can experiment with your physical keyboard hold Z key:
document.onkeypress = e => console.log(e.key);
So in Python with pynput just create one while
with the desired time to keep this running, however when testing with physical keyboard apparently there is a delay while holding down the key, I do not know how long this delay is, but it is likely to be between 0.04 seconds and 0.05 seconds, of course this is a time I suggested, the time is actually set by the operating system, example on Windows 10 with repetition rate:
So based on this answer using pyautogui I wrote the code that way:
import time
from pynput.keyboard import Key, Controller
def hold_key(key, seconds):
start = time.time()
while time.time() - start < seconds:
keyboard.press(key)
time.sleep(0.047)
keyboard.release(key)
keyboard = Controller()
time.sleep(2)
while True:
#pressiona por 5 segundos
hold_key('z', 2)
#espera 1 segundo para executar tecla A
time.sleep(1)
#pressiona por 4 segundos
hold_key('a', 2)
#espera 5 segundos para executar novamente
time.sleep(5)
Note that it is different from pyautogui’s . press behavior, if you are going to exchange pyunpt for pyautogui then you will not need the time.sleep(0.047)
, may be that the keyboard.pressed()
would solve, but I have no experience with this library, I read the documentation but really could not apply.
With pyautogui also could not solve according to the repetition rate of the operating system.
Perhaps another more experienced person can suggest a better answer in the future with pynput.