iterparse
は、ファイル全体を反復してツリーが構築され、要素が解放されません。これを行う利点は、要素が親の人を覚えており、祖先要素を参照するXPathを形成できることです。欠点は、多くのメモリを消費する可能性があることです。
あなたが解析して、いくつかのメモリを解放リザダリーズfast_iter
を使用するために:
あなたは、このように使用することができ
def fast_iter(context, func, *args, **kwargs):
"""
http://lxml.de/parsing.html#modifying-the-tree
Based on Liza Daly's fast_iter
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
See also http://effbot.org/zone/element-iterparse.htm
"""
for event, elem in context:
func(elem, *args, **kwargs)
# It's safe to call clear() here because no descendants will be
# accessed
elem.clear()
# Also eliminate now-empty references from the root node to elem
for ancestor in elem.xpath('ancestor-or-self::*'):
while ancestor.getprevious() is not None:
del ancestor.getparent()[0]
del context
:
def process_element(elem):
print "why does this consume all my memory?"
context = lxml.etree.iterparse('really-big-file.xml', tag='schedule', events = ('end',))
fast_iter(context, process_element)
私は非常にfast_iter
上記のどのthe articleをお勧めしますにもとづいて;大規模なXMLファイルを扱う場合は、特に興味深いはずです。
上記に示されたfast_iter
は、記事で と表示されているもののわずかに修正されたバージョンです。これは前の祖先を削除することに対してより積極的であるため、 はより多くのメモリを節約します。 Here you'll find a scriptであり、これは の違いを示しています。
ありがとう!あなたのソリューションと私が追加したものの両方がトリックを行うように見えますが、あなたと他の人が感じているのはより良い解決策です。あなたはどんな考えを持っていますか? –
あなたの解決策が働き、http://effbot.org/zone/element-iterparse.htm解決策はまだありませんでした(まだ私の記憶をすべて食べました) –
ありがとう!これは実際に動作するバージョンです。 Liza Daly、effbot、およびlxmlの公式ドキュメントのバージョンは、私のために多くのメモリを節約しませんでした。 – fjsj