PyAutoGui - Press key for X seconds

Robin Kühn picture Robin Kühn · Feb 8, 2018 · Viewed 10k times · Source

I'm currently working on a script that presses the 'w,a,s,d' keys in order to move a character in any game. For this to work, i need to have the 'w' key pressed for a specific amount of time. How can I achieve this?

I thought of something like:

pyautogui.keyDown('w')
time.sleep(2)
pyautogui.keyUp('w')

But this just pauses the whole program and no key is being pressed so this has no use to me.

Answer

Skandix picture Skandix · Feb 8, 2018

As said in the doc-string from pyautogui.keyDown():

Performs a keyboard key press without the release. This will put that key in a held down state.

NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field.


You need a different approach - you can may use pygame - with this

Or, if you want to stay with pyautogui you can try something like this:

def hold_W (hold_time):
    import time, pyautogui
    start = time.time()
    while time.time() - start < hold_time:
        pyautogui.press('w')