Search code examples
pythonpyautogui

Is there way to have code running concurrently (more specifically PyAutoGui)?


I have the following code

def leftdoor():
    press('a')
    pyautogui.sleep(1)
    press('a')

def rightdoor():
    press('d')
    pyautogui.sleep(1)
    press('d')

leftdoor()
rightdoor()

and when I run the code what happens is the letter A is pressed and 1 second is waited and then its pressed again. Then the same happens for the D key. However is there a way for me to be able to press them both down and express that in code by calling both functions and not having to wait for the .sleep of the previous function?


Solution

  • There are two ways to run your code concurrently:

    Combine the functions (might not be possible for large functions)

    In the case of your code, it would look like this:

    def door():
        press('a')
        press('d')
        sleep(1)
        press('a')
        press('d')
    
    door()
    

    If this isn't what you're looking for, use threading.

    Theading

    Here is a link to a tutorial on the module, and the code is below.

    from threading import Thread     # Module import
    rdt = Thread(target=rightdoor)   # Create two Thread objects
    ldt = Thread(target=leftdoor)
    rdt.start()                      # start and join the objects
    ldt.start()
    rdt.join()
    ldt.join()
    print("Finished execution")      # done!
    

    Note that using this does not absolutely guarantee that a and d will be pressed at the same time (I got a ~10 millisecond delay at max, and it might have been from the program I used to time it), but it should work for all purposes.