Skip to content

Instantly share code, notes, and snippets.

@FlafyDev
Created June 5, 2021 15:38
Show Gist options
  • Save FlafyDev/5030d689d532a0972b9d9f1ce6e55884 to your computer and use it in GitHub Desktop.
Save FlafyDev/5030d689d532a0972b9d9f1ce6e55884 to your computer and use it in GitHub Desktop.
Closes other instances of the same python script when called.
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