Search code examples
pythonpyautogui

pyautogui unable to recognize app opened by subprocess.Popen


I have a python-based GUI application running on Windows. Pyautogui able to locate the button if I manually launch the application, for example, in CMD, run python myapp.py

However, when I included the app opening operation in my script using subprocess.Popen, pyautogui is no longer recognize the button

Here's my code snippet

open_myapp = subprocess.Popen(['python', 'myapp.py'],
                stdout=subprocess.PIPE, 
                stderr=subprocess.PIPE)
r = pyautogui.locateCenterOnScreen(icon_locator.FILE_BTN)
print(r)
time.sleep(5)

Returns

None

If I comment out the subprocess, start myapp from Windows CMD manually, and rerun the code, I am able to get return position

Point(x=260, y=279)

Any ideas what's went wrong here?


Solution

  • You put the time.sleep(5) after the print you want. You need to put that command after the app opens and give it a time so that the script doesn't run before the app is visible on screen. It's just like Jasonharper said in his comment.

    It should be something like:

    ## whatever the command to open the app is ##
    time.sleep(5)
    print(r)
    

    Also define 'r' at the top of your file, just because it's better. That should do it.