8

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sande
  • 131
  • 1
  • 1
  • 9

1 Answers1

15

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")
Community
  • 1
  • 1
  • I think it's not one of default python libs, or I'm wrong? if so i found this lib https://pypi.python.org/pypi/psutil , do you this this one is right? – Sande Jun 07 '16 at 12:47
  • Yes, you right, this lib is not a default lib, but you link is correct, is the same module –  Jun 07 '16 at 12:51
  • Another question, I see this reacts in all python scripts As python.exe, but I would like to check seperate script not the main which has psutil – Sande Jun 07 '16 at 13:15
  • the p.cmdline() line returns a list like ["python.exe", "your_script.py"], using this you can check the second position in the list. –  Jun 07 '16 at 13:23
  • p.cmdline()[1] gets me 3 running programs : running.py ; Pinger.Py ; running.py; and it does't return true as it should – Sande Jun 07 '16 at 14:25
  • so i just edited it to if len(p.cmdline()) > 1 and "Pinger.py" in p.cmdline()[1]: print ("running") – Sande Jun 07 '16 at 14:28
  • Okay, it's changed =) –  Jun 07 '16 at 14:32