Created
June 5, 2021 15:38
-
-
Save FlafyDev/5030d689d532a0972b9d9f1ce6e55884 to your computer and use it in GitHub Desktop.
Closes other instances of the same python script when called.
This file contains 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 psutil | |
import os, inspect | |
def close_others(file=None): | |
if file is None: | |
this_path = os.path.abspath(inspect.stack()[-1].filename) | |
else: | |
this_path = os.path.realpath(file) | |
processes = [] | |
for pid in psutil.pids(): | |
try: | |
process = psutil.Process(pid) | |
if process.name() == "python.exe" or process.name() == "pythonw.exe": | |
processes.append(process) | |
except: | |
continue | |
for process in processes: | |
try: | |
if process.pid != os.getpid(): | |
script_path = os.path.abspath(process.cmdline()[1]) | |
if script_path == this_path: | |
process.terminate() | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment