我在使用yattag在我的python项目中生成HTML代码方面取得了相当好的效果。但是有些东西我不明白,实际上我在包文档中找不到它。我想重置文档的内容,以便从一个空页面开始。
请看下面的代码片段:
from yattag import Doc
doc, tag, text, line = Doc().ttl()
def main():
print('First page')
line('p', 'This is a line in the first page')
doc.nl()
print(doc.getvalue())
# here I would like to reset the doc content!!!
print('Second page')
line('p', 'This is a line in the second page')
doc.nl()
print(doc.getvalue())
if __name__ == "__main__":
main()产出如下:
首页
这是第一页的一行
第二页
这是第一页的一行
这是第二页的一行
我发现的一个解决方案是将doc, tag, text, line = Doc().ttl()移到主定义中,并在两个页面之间重新调用它,但我不确定内存泄漏是否存在。我需要手动执行垃圾收集吗?
非常感谢你的帮助!
发布于 2022-05-16 17:40:26
您可以通过对代码进行临时更改来快速回答这个问题,这样它就可以完成您所担心的在泄漏中需要垃圾收集的事情,如:
from yattag import Doc
doc, tag, text, line = Doc().ttl()
def main():
while True:
foo()
def foo():
doc, tag, text, line = Doc().ttl()
print('First page')
line('p', 'This is a line in the first page')
doc.nl()
print(doc.getvalue())
# here I would like to reset the doc content!!!
doc, tag, text, line = Doc().ttl()
print('Second page')
line('p', 'This is a line in the second page')
doc.nl()
print(doc.getvalue())
if __name__ == "__main__":
main()如果在多个地方调用Doc().ttl()是有问题的,这是我预料不到的,那么这个修改后的程序最终会崩溃。
https://stackoverflow.com/questions/72224584
复制相似问题