Sande
Sande

Reputation: 131

Checking if program is running programmatically

I was wondering how you could check if program is running using python and if not run it. I have two python scripts one is GUI which monitors another script.So basically if second script for some reason crashes I would like it start over.

n.b. I'm using python 3.4.2 on Windows.

Upvotes: 8

Views: 32336

Answers (1)

user6320679
user6320679

Reputation:

The module psutil can help you. To list all process runing use:

import psutil

print(psutil.pids()) # Print all pids

To access the process information, use:

p = psutil.Process(1245)  # The pid of desired process
print(p.name()) # If the name is "python.exe" is called by python
print(p.cmdline()) # Is the command line this process has been called with

If you use psutil.pids() on a for, you can verify all if this process uses python, like:

for pid in psutil.pids():
    p = psutil.Process(pid)
    if p.name() == "python.exe":
        print("Called By Python:"+ str(p.cmdline())

The documentation of psutil is available on: https://pypi.python.org/pypi/psutil

EDIT 1

Supposing if the name of script is Pinger.py, you can use this function

def verification():
    for pid in psutil.pids():
        p = psutil.Process(pid)
        if p.name() == "python.exe" and len(p.cmdline()) > 1 and "Pinger.py" in p.cmdline()[1]:
            print ("running")

Upvotes: 15

Related Questions