El-Chief
El-Chief

Reputation: 384

Checking for a running python process using python

I have a python script called speech.pyw. I don't want it showing up on the screen when run so I used that extension.

How can I check using another python script whether or not this script is running? If it isn't running, this script should launch it.

Upvotes: 1

Views: 521

Answers (2)

andrew pate
andrew pate

Reputation: 4299

!/usr/bin/env python2
import psutil
import sys

processName="wastetime.py"

def check_if_script_is_running(script_name):
    script_name_lower = script_name.lower()
    for proc in psutil.process_iter():
        try:
            for element in proc.cmdline():
                if element.lower() == script_name_lower:
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

print(check_if_script_is_running(processName))
sys.stdin.readline()

Upvotes: 0

Majora320
Majora320

Reputation: 1351

Off the top of my head, there are at least two ways to do this:

  • You could make the script create an empty file in a specific location, and the other script could check for that. Note that you might have to manually remove the file if the script exits uncleanly.
  • You could list all running processes, and check if the first one is among those processes. This is somewhat more brittle and platform-dependant.

An alternative hybrid strategy would be for the script to create the specific file and write it's PID (process id) to it. The runner script could read that file, and if the specified PID either wasn't running or was not the script, it could delete the file. This is also somewhat platform-dependant.

Upvotes: 1

Related Questions