Check If a Python Script Is Already Running in Windows

Check if a process is running or not on Windows?

You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.

import psutil    
"someProgram" in (p.name() for p in psutil.process_iter())

Checking if program is running programmatically

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")


Related Topics



Leave a reply



Submit