Search code examples
pythonpython-3.xpyautogui

pyautogui slight delay in key presses


So I want to hold down the c key for lets say 0.2 seconds and release it. To do that I thought using pyautogui.keyDown("") and keyUp("") would help but it has a slight delay in it so like when I do

pyautogui.keyDown("c")
time.sleep(0.2)
pyautogui.keyUp("C")

What it does is holds the key "c" for longer than 0.2 seconds, I just want it to press c for 0.2 seconds. My main code is:

import pyautogui
import time
time.sleep(0.5)

pyautogui.keyDown("c")
time.sleep(0.2)
pyautogui.keyUp("c")
time.sleep(0.5)
pyautogui.keyDown("space")
pyautogui.keyUp("space")
time.sleep(0.5)
pyautogui.keyDown("c")
time.sleep(0.2)
pyautogui.keyUp("c")
time.sleep(0.5)
pyautogui.keyDown("space")
pyautogui.keyUp("space")

The time.sleep is the delay I want it to be but it has a delay on its own without the time.sleep.

EDIT: Solution was to disable failsafe


Solution

  • I looked at the documentation and apparently there is a .1 second delay between pyautogui commands, to allow you to break into the operation manually in case of runaway, documented here: #fail-safe. They warn against it, but you might be able to do this:

    import pyautogui
    import time
    
    KEY_C = "c"
    KEY_SPACE = "space"
    
    time.sleep(0.5)
    
    pyautogui.FAILSAFE = False # danger zone
    pyautogui.keyDown(KEY_C)
    time.sleep(0.2)
    pyautogui.keyUp(KEY_C)
    pyautogui.keyDown(KEY_SPACE)
    pyautogui.keyUp(KEY_SPACE)
    pyautogui.FAILSAFE = True # out of danger
    
    # do it again
    
    time.sleep(0.5)
    pyautogui.FAILSAFE = False
    pyautogui.keyDown(KEY_C)
    time.sleep(0.2)
    pyautogui.keyUp(KEY_C)
    pyautogui.keyDown(KEY_SPACE)
    pyautogui.keyUp(KEY_SPACE)
    pyautogui.FAILSAFE = True