Last active
December 20, 2018 12:10
-
-
Save scholi/37a1572c18c7a2ab925e16e4ce2e4aed to your computer and use it in GitHub Desktop.
Memory watchdog for python process.
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
""" | |
Python 64bit on windows can potentially use all your RAM and freeze your computer. | |
Here is a small watchdog which will automatically kill the python process which use | |
the highest amount of RAM if the RAM consumption is higher than 95% | |
""" | |
import psutil | |
import time | |
import sys | |
def get_max_ram_proc(): | |
python = [] | |
for proc in psutil.process_iter(): | |
if proc.name() == "python.exe": | |
python.append(proc) | |
return max([(p, p.memory_info().wset) for p in python], key=lambda x: x[1]) | |
WIDTH = 73 | |
i = 0 | |
while True: | |
mem = psutil.virtual_memory() | |
c = int(psutil.cpu_percent()*WIDTH/100) | |
p = int(mem.percent*WIDTH/100) | |
proc, ramu = get_max_ram_proc() | |
sys.stdout.write("\033[2J\033[H") | |
sys.stdout.write("RAM |"+"="*p+" "*(WIDTH-p)+"|\033[E") | |
sys.stdout.write("CPU |"+"="*c+" "*(WIDTH-c)+"|\033[E") | |
sys.stdout.write("Time: "+time.strftime("%H:%M:%S")+"\033[E") | |
sys.stdout.write("Max CPU proc: {} (PID={}, RAM={:.1f}Mb)".format(proc.name(), proc.pid, ramu/1024**2)) | |
i = (i+1)%4 | |
sys.stdout.flush() | |
print(proc) | |
if mem.percent>95: | |
print("Killing process PID=", proc.pid) | |
proc.kill() | |
time.sleep(.2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment