gpt4 book ai didi

python - Python代码中如何处理 "MemoryError"

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:35 24 4
gpt4 key购买 nike

我有一段 python 代码会在一段时间后生成一个 MemoryError。我知道它会消耗大量内存。因此,我决定将代码放在 try/except block 中,这样框架看起来如下所示:

while True:

while True:

try:
#---- do some stuff

except MemoryError as err:
print(err)
break

因此,我的想法是,如果发生 MemoryError 并且因为我有一个外部 while-,则跳出第一个 while 循环循环,它会再次启动程序。

目前看来它可以工作,但我不确定。过了一会儿,它又停止了,我需要重新启动程序。有人知道更好的解决方案,以便程序可以在 MemoryError 之后再次运行吗?

最佳答案

请注意,Python 只会在意识到会预先过度使用内存时抛出 MemoryError。如果它是偶然发生的(或被 Python“未注意到”),那么你就不走运了。 documentation已经提到了这一点:

MemoryError

Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.

因此,如果没有什么可挽救的或解释器无法恢复,则没有 MemoryError


一个好的方法需要知道您在做什么以及如何做。在大多数情况下,生成器(参见例如 PEP 289 on generator expressions )或 map-reduce approaches可以为您节省大量内存。这些可能也适用于此。

关于python - Python代码中如何处理 "MemoryError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com