我正在尝试将Python程序的RAM使用限制为一半,以便在使用所有RAM时不会完全冻结,为此我使用以下代码无效,我的笔记本电脑仍在冻结:
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)
Run Code Online (Sandbox Code Playgroud)
我正在使用我从main
函数调用的其他函数.
我究竟做错了什么?
提前致谢.
PD:我已经搜索了这个并找到了我已经提供的代码,但它仍然没有工作......
Uli*_* CT 19
好的,我做了一些研究,发现了一个从Linux系统获取内存的功能:确定Python中的空闲RAM并稍微修改它以获得可用的可用内存并将可用的最大内存设置为一半.
码:
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)
Run Code Online (Sandbox Code Playgroud)
将其设置为半该生产线是resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard))
在那里get_memory() * 1024 / 2
将它设置为一半(它以字节为单位).
希望这可以在将来帮助他人同样的事情!=)
小智 9
我修改了@Ulises CT 的答案。因为我觉得把原有的功能改动太多不太好,所以我把它变成了一个装饰器。我希望它有帮助。
import resource
import platform
import sys
def memory_limit(percentage: float):
"""
??linux???????
"""
if platform.system() != "Linux":
print('Only works on linux!')
return
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 * percentage, 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
def memory(percentage=0.8):
def decorator(function):
def wrapper(*args, **kwargs):
memory_limit(percentage)
try:
function(*args, **kwargs)
except MemoryError:
mem = get_memory() / 1024 /1024
print('Remain: %.2f GB' % mem)
sys.stderr.write('\n\nERROR: Memory Exception\n')
sys.exit(1)
return wrapper
return decorator
@memory(percentage=0.8)
def main():
print('My memory is limited to 80%.')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13880 次 |
最近记录: |