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.

5
  • Google around and see what pidfile is, maybe that will solve your problem. Commented Jun 7, 2016 at 12:22
  • This might help you: stackoverflow.com/questions/1632234/… Commented Jun 7, 2016 at 12:42
  • sudo apt-get install supervisor Commented Jun 7, 2016 at 12:42
  • supervisor isn't right here, I need windows management adn supervisor is unix like Commented Jun 7, 2016 at 13:17
  • jeromejaglale.com/doc/python/check_script_not_already_running Commented Dec 2, 2017 at 0:27

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

7 Comments

I think it's not one of default python libs, or I'm wrong? if so i found this lib pypi.python.org/pypi/psutil , do you this this one is right?
Yes, you right, this lib is not a default lib, but you link is correct, is the same module
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
the p.cmdline() line returns a list like ["python.exe", "your_script.py"], using this you can check the second position in the list.
p.cmdline()[1] gets me 3 running programs : running.py ; Pinger.Py ; running.py; and it does't return true as it should
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.