How to simulate pressing a key for a certain time?

Asked

Viewed 500 times

0

I was trying to make a Python BOT that held the z key for 4 seconds and then released, I tried to use the pynput, but when using the keyboard.press('z'), the command clicked only once and did not keep the key pressed for 4 seconds.

Code:

import pynput
import time
from pynput.keyboard import Key, Controller
keyboard = Controller()

time.sleep(2)
while True:
    keyboard.press('z')
    time.sleep(5)
    keyboard.release('z')
    time.sleep(1)

1 answer

2

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:

taxa de repetição do teclado no Windows 10

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.