什么都没有为我工作!
所以我写了一个脚本来监视内存使用情况。如果内存消耗增加了阈值,它将首先尝试清除RAM缓存。您可以在脚本上配置此阈值。如果直到那时内存消耗仍未低于阈值,它将以内存消耗的降序开始杀死进程,直到内存消耗低于阈值。我已将其默认设置为96%。您可以通过在脚本中更改变量RAM_USAGE_THRESHOLD的值来进行配置。
我同意杀死消耗大量内存的进程不是完美的解决方案,但是最好杀死一个应用程序而不是丢失所有工作!如果RAM使用率增加阈值,脚本将向您发送桌面通知。如果它杀死任何进程,它也会通知您。
#!/usr/bin/env python
import psutil, time
import tkinter as tk
from subprocess import Popen, PIPE
import tkinter
from tkinter import messagebox
root = tkinter.Tk()
root.withdraw()
RAM_USAGE_THRESHOLD = 96
MAX_NUM_PROCESS_KILL = 100
def main():
if psutil.virtual_memory().percent >= RAM_USAGE_THRESHOLD:
# Clear RAM cache
mem_warn = "Memory usage critical: {}%\nClearing RAM Cache".\
format(psutil.virtual_memory().percent)
print(mem_warn)
Popen("notify-send \"{}\"".format(mem_warn), shell=True)
print("Clearing RAM Cache")
print(Popen('echo 1 > /proc/sys/vm/drop_caches',
stdout=PIPE, stderr=PIPE,
shell=True).communicate())
post_cache_mssg = "Memory usage after clearing RAM cache: {}%".format(
psutil.virtual_memory().percent)
Popen("notify-send \"{}\"".format(post_cache_mssg), shell=True)
print(post_cache_mssg)
if psutil.virtual_memory().percent < RAM_USAGE_THRESHOLD:
print("Clearing RAM cache saved the day")
return
# Kill top C{MAX_NUM_PROCESS_KILL} highest memory consuming processes.
ps_killed_notify = ""
for i, ps in enumerate(sorted(psutil.process_iter(),
key=lambda x: x.memory_percent(),
reverse=True)):
# Do not kill root
if ps.pid == 1:
continue
elif (i > MAX_NUM_PROCESS_KILL) or \
(psutil.virtual_memory().percent < RAM_USAGE_THRESHOLD):
messagebox.showwarning('Killed proccess - save_hang',
ps_killed_notify)
Popen("notify-send \"{}\"".format(ps_killed_notify), shell=True)
return
else:
try:
ps_killed_mssg = "Killed {} {} ({}) which was consuming {" \
"} % memory (memory usage={})". \
format(i, ps.name(), ps.pid, ps.memory_percent(),
psutil.virtual_memory().percent)
ps.kill()
time.sleep(1)
ps_killed_mssg += "Current memory usage={}".\
format(psutil.virtual_memory().percent)
print(ps_killed_mssg)
ps_killed_notify += ps_killed_mssg + "\n"
except Exception as err:
print("Error while killing {}: {}".format(ps.pid, err))
else:
print("Memory usage = " + str(psutil.virtual_memory().percent))
root.update()
if __name__ == "__main__":
while True:
try:
main()
except Exception as err:
print(err)
time.sleep(1)
将代码保存在一个名为save_hang.py的文件中。运行脚本为:
sudo python save_hang.py
请注意,该脚本仅与Python 3兼容,并且需要您安装tkinter软件包。您可以将其安装为:
sudo apt-get install python3-tk
希望这可以帮助...