问题描述
我试图将 Python 程序的 RAM 使用量限制为一半,以便在使用所有 RAM 时它不会完全冻结,为此我使用了以下代码,但我的笔记本电脑仍然无法正常工作冻结:
导入系统导入资源定义内存限制():rsrc = 资源.RLIMIT_DATA软,硬 = resource.getrlimit(rsrc)软/= 2资源.setrlimit(rsrc,(软,硬))如果 __name__ == '__main__':memory_limit() # 将最大内存使用限制为一半尝试:主要的()除了内存错误:sys.stderr.write('超出最大内存')sys.exit(-1)
我正在使用从 main
函数调用的其他函数.
我做错了什么?
提前致谢.
PD:我已经搜索过这个并找到了我已经放置的代码,但它仍然无法正常工作......
好吧,我做了一些研究,找到了一个从 Linux 系统获取内存的函数:确定 Python 中的空闲 RAM,我对其进行了一些修改以获取可用内存并将最大可用内存设置为其一半.>
代码:
def memory_limit():软,硬 = resource.getrlimit(resource.RLIMIT_AS)resource.setrlimit(resource.RLIMIT_AS,(get_memory() * 1024/2, hard))def get_memory():使用 open('/proc/meminfo', 'r') 作为内存:free_memory = 0因为我在内存中:sline = i.split()如果 str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):free_memory += int(sline[1])返回 free_memory如果 __name__ == '__main__':memory_limit() # 将最大内存使用限制为一半尝试:主要的()除了内存错误:sys.stderr.write('\n\n错误:内存异常\n')sys.exit(1)
将其设置为一半的行是 resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024/2, hard))
where get_memory() * 1024/2
将其设置为一半(以字节为单位).
希望这可以帮助以后遇到同样问题的人!=)
I'm trying to limit the RAM usage from a Python program to half so it doesn't totally freezes when all the RAM is used, for this I'm using the following code which is not working and my laptop is still freezing:
import sys
import resource
def memory_limit():
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
soft /= 2
resource.setrlimit(rsrc, (soft, hard))
if __name__ == '__main__':
memory_limit() # Limitates maximun memory usage to half
try:
main()
except MemoryError:
sys.stderr.write('MAXIMUM MEMORY EXCEEDED')
sys.exit(-1)
I'm using other functions which I call from the main
function.
What am I doing wrong?
Thanks in advance.
PD: I already searched about this and found the code I've put but it's still not working...
Ok so I've made some research and found a function to get the memory from Linux systems here: Determine free RAM in Python and I modified it a bit to get just the free memory available and set the maximum memory available as its half.
Code:
def memory_limit():
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard))
def get_memory():
with open('/proc/meminfo', 'r') as mem:
free_memory = 0
for i in mem:
sline = i.split()
if str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
free_memory += int(sline[1])
return free_memory
if __name__ == '__main__':
memory_limit() # Limitates maximun memory usage to half
try:
main()
except MemoryError:
sys.stderr.write('\n\nERROR: Memory Exception\n')
sys.exit(1)
The line to set it to the half is resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard))
where get_memory() * 1024 / 2
sets it to the half (it's in bytes).
Hope this can help others in future with the same matter! =)
这篇关于将 RAM 使用限制为 python 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!