Advertisement
A_GUES

Stop CPU, RAM,

Jul 29th, 2023
1,347
0
Never
6
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.54 KB | None | 0 0
  1. import os
  2. import psutil
  3. import sys
  4.  
  5. def check_resources(limit_cpu_percent, limit_ram_mb):
  6.     pid = os.getpid()
  7.     py = psutil.Process(pid)
  8.  
  9.     cpu_usage = py.cpu_percent()
  10.     ram_usage = py.memory_info()[0] / 2. ** 20  # Convert bytes to MB
  11.  
  12.     if cpu_usage > limit_cpu_percent or ram_usage > limit_ram_mb:
  13.         print('CPU or Memory limit exceeded...stopping')
  14.         sys.exit()
  15.  
  16. # Use it in your code like this
  17. while True:  # or your main loop
  18.     # your code here
  19.     check_resources(limit_cpu_percent=80, limit_ram_mb=500)
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement