Tuesday, January 28, 2020

Python - check if python is running or not

If you scheduled some jobs to run on schedule, and you don't want to start the process again while it is still running, then you can use the following code to check if it is still running. If not, it will start the job; if it is still running, it won't restart the process again.


psutil
psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoringprofiling and limiting process resources and management of running processes


import psutil
import os
from subprocess import call


def is_running(script):
    for q in psutil.process_iter():
        if q.name().startswith('python'):
            if len(q.cmdline()) > 1 and script in q.cmdline()[1] and q.pid != os.getpid():
                print("'{}' Process is already running".format(script))
                return True
    return False

if __name__ == "__main__":
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'schedule_scripts.py')
    if not is_running(file_path):
        call(["python", file_path])

No comments:

Post a Comment