Last active
February 22, 2022 18:56
-
-
Save elibroftw/44844582287ce7386d1d9d5060e52972 to your computer and use it in GitHub Desktop.
A Python program to detect if an instance of a program/process is already running. [Windows]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import platform | |
from subprocess import Popen, PIPE, DEVNULL | |
def get_running_processes(look_for='', pid=None, add_exe=True): | |
# TODO: Linux implementation | |
cmd = f'tasklist /NH' | |
if look_for: | |
if not look_for.endswith('.exe') and add_exe: | |
look_for += '.exe' | |
cmd += f' /FI "IMAGENAME eq {look_for}"' | |
if pid is not None: | |
cmd += f' /FI "PID eq {pid}"' | |
p = Popen(cmd, shell=True, stdout=PIPE, stdin=DEVNULL, stderr=DEVNULL, text=True, encoding='iso8859-2') | |
p.stdout.readline() | |
for task in iter(lambda: p.stdout.readline().strip(), ''): | |
m = re.match(r'(.+?) +(\d+) (.+?) +(\d+) +(\d+.* K).*', task) | |
if m is not None: | |
yield {'name': m.group(1), 'pid': int(m.group(2)), 'session_name': m.group(3), | |
'session_num': m.group(4), 'mem_usage': m.group(5)} | |
def is_already_running(look_for='Music Caster', threshold=1, pid=None) -> bool: | |
""" | |
Returns True if more processes than `threshold` were found | |
""" | |
if platform.system() == 'Windows': | |
for _ in get_running_processes(look_for=look_for, pid=pid): | |
threshold -= 1 | |
if threshold < 0: | |
return True | |
else: # Linux | |
p = Popen(['ps', 'h', '-C', look_for, '-o', 'comm'], stdout=PIPE, stdin=PIPE, stderr=DEVNULL, text=True) | |
# todo: threshold feature | |
return p.stdout.readline().strip() != '' | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment