运行 这个循环会长期阻塞我的记忆吗?

Am I going to clog my memory by running this loop long-term?

感谢您抽空查看这个问题!

我正在为 Raspberry Pi 零上的 运行 创建一个 Python 脚本。这个想法是它会在附加屏幕上无限循环地一次滚动一行很长的文本(指环王三部曲)。

我已经得到了使用以下代码和示例文本的循环。但是,我不是很熟悉 Python 使用内存的方式。随着每一行的生成和打印,此方法是否会继续占用越来越多的内存(或者,换句话说,这最终会冻结吗)?

import time
import tkinter as tk

book = open('ave.txt', 'r')
lines = book.readlines()

position = 0

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.text = tk.Text(self, height=6, width=40)
        self.text.pack(side="left", fill="both", expand=True)
        
        self.readbook()

    def readbook(self):
        global position
        self.text.insert("end", lines[position])
        self.text.see("end")
        position += 1
        self.after(1000, self.checkloop)

    def checkloop(self):
        global position
        if position == 6:
            position = 0
            self.text.insert("end", '\n' + '\n')
            self.readbook()
        else:
            self.readbook()

if __name__ == "__main__":
    root =tk.Tk()
    frame = Example(root)
    frame.pack(fill="both", expand=True)
    root.mainloop()

(感谢 Bryan Oakley,他在 上的回答中提供了此实现的框架)

这里有很多复杂的问题没有解决。假设你有 512mb,我不这么认为。您的聚合文档的大小是多少? readlines() 的文档指出它将整个文档加载到内存中(它已经在内存中打开因此是一个副本),将每一行解析为一个字符串,并将它们存储在一个数组中。如果整个文档大约 25mb,那应该没问题。您总是可以使用类似

的方式遍历这些行
with open('lor.txt') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

这样您就不会一次将整个文档重新加载到内存中。