Skip to content

Instantly share code, notes, and snippets.

@afiodorov
Last active July 22, 2022 23:37
Show Gist options
  • Save afiodorov/549137a9aa2e076c4fe774c8ed652987 to your computer and use it in GitHub Desktop.
Save afiodorov/549137a9aa2e076c4fe774c8ed652987 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import psutil
import time
if __name__ == "__main__":
while True:
procs = []
for proc in psutil.process_iter():
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
pinfo['mem%'] = proc.memory_percent()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
else:
procs.append(pinfo)
total = sum((p['mem%'] for p in procs))
if total > 99:
top = max(procs, key=lambda p: p['mem%'])
print(f"killing {top['name']}...")
try:
psutil.Process(top['pid']).kill()
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
time.sleep(20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment