如何处理“ MemoryError”?用Python代码 [英] How to deal with "MemoryError" in Python code

查看:148
本文介绍了如何处理“ MemoryError”?用Python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些python代码,过一段时间后会生成 MemoryError 。我知道它会占用大量内存。
因此,我决定将代码放在 try / except 块中,以便使框架看起来像以下内容:

I have some piece of python code which generates a MemoryError after a while. I know that it consumes a lot of memory. So, I decided to put the code within a try/except block so that the skeleton looks like the following:

while True:

      while True:

            try:
            #---- do some stuff

            except MemoryError as err:
                   print(err)
                   break

所以,我的想法是,如果发生 MemoryError 并打破第一个 while 循环,因为我有一个外部 while -循环,它将再次启动程序。

So, my idea is to break out of the first while-loop if a MemoryError occurs and since I have an outer while-loop, it will start the program again.

似乎它适用于此刻,但我不确定。一段时间后,它再次停止,我需要再次重新启动该程序。
是否有人知道更好的解决方案,以便程序可以在 MemoryError 之后再次运行?

It seems that it works for the moment but I am not sure. After a while, it stops again and I need to restart the program again. Does somebody know a better solution so that the program can run after the MemoryError again?

推荐答案

在不知道您在这次尝试中做什么的情况下很难评估要做什么,但我会尝试的。

It is hard to assess what to do without knowing what do you do inside this try but I will try.

关于继续try-except块。恐怕您无法执行此操作。

Frstrly, regarding continuing the try-except block. I am afraid you cannot do this.

这么短的答案是您不能回去尝试阻止发生异常的地方,您可以转到第一行尝试

可以执行的操作:

我通常会像以下那样处理我的异常。像这样创建 True 循环:

I usually handle my exceptions like the following. Create while True loop as such:

while True:
    try:
        #some code here
    except SomeException:
        continue

现在,您可以继续尝试在异常发生后进行尝试。

Now you can continue to try after exception occured.

第二种方式(但不推荐)是使用某些函数嵌入代码并递归执行。

Second way (but not reccomended) is to embedd your code using some function and recursively execute it.

def foo():
    try:
        while True:
            foo2()
    except StopIteration:
        #end code

def foo2():
    while True:
        try:
            #some code here
        except MemoryError:
            foo2()
            raise StopIteration()

但是这非常危险,但是如果您的内存被使用的次数不多(<1000),这可能是个好方法您需要在之前做点什么但是您需要密切注意解决方案。

However this is very DANGEROUS however if your memory is being exceeded not many times (<1000) this can be okay way to go if you need to do something before while True however you need to watch solution closely.

这篇关于如何处理“ MemoryError”?用Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆