Checking if a process still exists

Last edited on

Synopsis

It may be required to know when a process has exited, for example to ensure that following actions, steps and test cases do not run into an error when trying to start the same (still running) process/application again.

Python

# See
#  https://doc.qt.io/squish/squish-api.html#rgs-remotesystem
from remotesystem import RemoteSystem

def main():
    # See
    #  https://doc.qt.io/squish/squish-api.html#startapplication-function
    ctx = startApplication("myaut")

    #...



    # Copy PID, as the application context
    # may go away:
    # See
    #  https://doc.qt.io/squish/squish-api.html#application-context
    pid = ctx.pid

    # Initiate AUT shutdown somehow, here we
    # use ApplicationContext.detach():
    # See
    #  https://doc.qt.io/squish/squish-api.html#applicationcontext-detach-function
    ctx.detach()



    # Wait for process to have exited:
    while process_exists(pid):
        test.log("Process still exists: PID: %s" % pid)
        snooze(0.5)

def process_exists(pid, remoteSystem=None):
    if remoteSystem is None:
        remoteSystem = RemoteSystem()

    # Check if process is still running for Windows:
    try:
        if "ProcessId" in remoteSystem.execute(["wmic", "PROCESS", "where", "ProcessId=%s" % pid, "GET", "ProcessId"])[1]:
            return True
    except:
        pass

    # Check if process is still running for Unix:
    try:
        if remoteSystem.execute(["ps", "--pid", "%s" % pid])[0] == "0":
            return True
    except:
        pass
    return False
test.py