Python that Checks if Another Python Script is Running

Published by Brandon on

Check for Running Python

Today we are going to show how to write a python script that checks if other python scripts are running. Perhaps you have a script that runs often or or maybe all the time and you want another script to periodically check if it is indeed running.

The first thing you will need to do is pip install psutil. Psutil is a module that can give us information about running processes.

python -m pip install psutil

Now that we have psutil, let’s create a list of all the running processes on our PC. Here’s a list comprehension to do just that using the process_iter().

import psutil

processes = [p for p in psutil.process_iter()]

print(processes)

So this is a step closer, but how do we narrow it down to just the processes running python?

Easily, we can say only put those processes in a list where python is in the name of the process.

import psutil

processes = [p for p in psutil.process_iter() if 'python' in p.name()]

print(processes)

Now we just get a list of processes that are running python. How do we now know what python process is running what python script. We can use p.cmdline() instead of just p in the list comprehension to gain more info about how the process was called.

import psutil

processes = [p.cmdline() for p in psutil.process_iter() if 'python' in p.name()]

print(processes)

Notice that the list is now a list of lists with the second item in the list being what the name of the script is. Here, you may notice an issue. The name of the script that this python above is in is listed. We probably don’t want that listed cause it’s obviously running since we are checking for others. Let’s not include the script doing the checking.

import psutil


# Ignore this script
processes = [p.cmdline() for p in psutil.process_iter() if 'python' in p.name() and 'testrunning.py' not in p.cmdline()[1]]

print(processes)

Want to see more of this in a video? Check out my video on this.

Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *