Search code examples
pythonpython-3.xpynput

How to keep pressing certain key for certain amount of time in python?


I am trying to automate android game using python but I end up in a situation where I have to keep pressing CTRL key and use mouse wheel to zoom out.

I installed Pynput and tried this command

keyboard.press('a')
time.sleep(3)
keyboard.release('a')

But it doesn't keep pressing a key for 3 seconds but press only once.

Can anyone pls tell me a simple script, where it will keep pressing CTRL key and use mouse wheel to zoom out?


Solution

  • I'm assuming you want the key to be pressed over and over again rather than being held down (which is what I think your code above is doing).

    You got two options that I know of. The easiest, by far, is to use floats alongside sleep, and do something like this:

    timer = 0
    
    while timer < 3:
        time.sleep(0.1)
        timer += 0.1
        keyboard.press('a')
    

    This will press the 'a' key every 0.1 seconds until 3 seconds is reached.

    Otherwise, you could import the 'threading' module which lets you run code in paralel, and therefore run a loop and a timer simultaneously. This is probably a huge can of worms for what you're trying to do. The code below presses the 'a' key as fast as possible until the three second timer ends, it doesn't exit threads or anything though, which is why this is probably a bad approach:

    global_timer = 0
    
    def keep_pressing_a():
        while global_timer <= 3:
            keyboard.press('a')
    
    def count_to_three():
        global global_timer
        keep_counting = True
        while keep_counting:
            time.sleep(1)
            global_timer += 1
            if global_timer >= 3:
                keep_counting  = False
    
    threading.Thread(target=count_to_three).start()
    threading.Thread(target=something).start()