有谁知道在 Python 中生成非常大的 xml 文件(例如 100-500 MiB)的内存高效方法?
我一直在使用 lxml,但内存使用量已达到顶峰。
最佳答案
也许您可以使用模板引擎而不是自己生成/构建 xml?
Genshi例如基于 xml 并支持流式输出。一个非常基本的例子:
from genshi.template import MarkupTemplate
tpl_xml = '''
<doc xmlns:py="http://genshi.edgewall.org/">
<p py:for="i in data">${i}</p>
</doc>
'''
tpl = MarkupTemplate(tpl_xml)
stream = tpl.generate(data=xrange(10000000))
with open('output.xml', 'w') as f:
stream.render(out=f)
这可能需要一段时间,但内存使用率仍然很低。
Mako 的相同示例模板引擎(不是“本地”xml),但速度更快:
from mako.template import Template
from mako.runtime import Context
tpl_xml = '''
<doc>
% for i in data:
<p>${i}</p>
% endfor
</doc>
'''
tpl = Template(tpl_xml)
with open('output.xml', 'w') as f:
ctx = Context(f, data=xrange(10000000))
tpl.render_context(ctx)
最后一个示例在我的笔记本电脑上运行了大约 20 秒,生成了一个(诚然非常简单)151 MB 的 xml 文件,完全没有内存问题。 (根据 Windows 任务管理器,它一直保持在 10MB 左右)
根据您的需要,这可能是一种比使用 SAX 等更友好、更快速的生成 xml 的方法...查看文档以了解您可以使用这些引擎做什么(还有其他引擎,我刚刚挑选出来这两个作为例子)
关于python - 在 Python 中生成非常大的 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3049188/