【问题标题】:How to free memory in python?如何在python中释放内存?
【发布时间】:2023-04-05 19:40:01
【问题描述】:

我是 python 的新手,我需要整天运行脚本。但是,脚本使用的内存随着时间的推移不断增加,直到 python 崩溃......我尝试了一些东西但没有任何效果:(也许我做错了什么我不知道。这是我的代码的样子:

while True:
  try:  

    import functions and modules...
    Init_Variables = ...
    def a bunch of functions...

    def clearall(): #Function to free memory
        all = [var for var in globals() if var[0] != "_" and var != gc]
        for var in all:
            del globals()[var]
        print('Cleared !')
        gc.collect()
        TimeLoop()  #Getting out of "try" here because TimeLoop isn't defined anymore            

    def TimeLoop():

        for i in range (1,101):     
            do stuff...

        # Free memory after 100 iterations #############################
        clearall()

    TimeLoop() # Launches my function when i first start the script

  except Exception as e:
    print(e)
    continue
  break

在大约 50.000 次“do stuff...”迭代之后,python 使用了大约 2GB 的 RAM,然后崩溃了 :( 我花了几个小时试图解决这个问题,但似乎没有任何效果。任何帮助将不胜感激! :D

【问题讨论】:

  • 很有可能,与其连续运行同一个脚本,不如设置一个cronjob间隔运行脚本。
  • 就像运行脚本 X 分钟然后杀死并重新启动它??有点残酷,但应该工作^^'。但是我想找一个更柔和的工作哈哈:)
  • 没有。运行脚本,让它完成,然后一分钟后重新运行。

标签: python memory-management crash out-of-memory infinite-loop


【解决方案1】:

一旦不再存在对对象的引用,Python 就会自动释放内存。您不应该尝试自己释放内存。您似乎使用递归调用,这意味着每次迭代中的每个变量都保存在内存中。

最佳做法是,仅使用局部变量,保持函数简短,避免递归,不要使用循环引用。

所以你的脚本应该很简单:

import functions and modules...
# no global variables
def a bunch of functions...

def main():
    while True:     
        call_function_to_do_stuff()
        # python frees memory automatically after each function call

if __name__ == '__main__':
    main() # Launches my function when i first start the script

【讨论】:

  • 这正是它之前的样子,但我遇到了这个内存问题。这就是为什么我制作了这个 clearall() 函数和 while 循环。我循环向网站发出几个请求,但我得到的答案似乎是无限存储的。而且我不知道如何在没有递归调用的情况下提出这些请求:(
  • 那你应该把问题当成真正的问题。
【解决方案2】:

使用 python64,并在 x 时间后将大数据变量转储为 null。我最近设法让一个程序使用 8gb ram 并且 python64 运行良好

【讨论】:

  • 我确实是在 32 位运行,我会试试这个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
相关资源
最近更新 更多