Search code examples
pythonsubprocesspython-os

Python run app and wait for it to load before interacting


I am trying to open an application and interact with it. I am facing an issue where I do open application, but due to its size it takes a while before it appears, therefore I'd like to catch the app object in a dynamic/pythonic manner.

import os
import subprocess
import win32com.client

timeout = 5

big_app = r'C:\Path2BigApp\app.exe'
os.startfile(big_app)

try:
    my_app_obj = win32com.client.GetObject("AppName")
    # further steps with my_app_obj
except:
    print("nay")

I've tried os.startfile(big_app) which starts app but does not wait for app to be successfully opened, so it always evaluates for "nay", subprocess.call(big_app, timeout) which opens app and freezes python until app is terminated and then evaluates the following code, subprocess.Popen(big_app) what gives the same result as the first option, and subprocess.Popen(big_app).wait(timeout) & subprocess.Popen(big_app).communicate(timeout) which result only in TimeoutExpired error, since no interaction/termination there. I know I could employ some wait/sleep operation in loop, but I am hoping there is more pythonic way to solve that problem. Do you got any advice on that?


Solution

  • Do you have a method to check if your app is loaded successfully?

    I'd start a while loop that would try to detect when an app is loaded. If it's not loaded - wait a second and repeat, if loaded then proceed.