iterparse
पूरे फ़ाइल पर एक पेड़ बनाया गया है और कोई तत्व मुक्त नहीं किया गया है। ऐसा करने का लाभ यह है कि तत्व याद करते हैं कि उनके माता-पिता कौन हैं, और आप XPaths बना सकते हैं जो पूर्वजों के तत्वों को संदर्भित करते हैं। नुकसान यह है कि यह बहुत सारी स्मृति का उपभोग कर सकता है।
कुछ स्मृति मुक्त करने के लिए के रूप में आप को पार्स, का उपयोग लिज़ा डैली के 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)
मैं अत्यधिक the article जो ऊपर fast_iter
पर की सिफारिश आधारित है; यदि आप बड़ी एक्सएमएल फाइलों से निपट रहे हैं तो यह आपके लिए विशेष रूप से दिलचस्प होना चाहिए।
उपरोक्त प्रस्तुत fast_iter
लेख में दिखाए गए एक का थोड़ा संशोधित संस्करण है। यह पिछले पूर्वजों को हटाने के बारे में अधिक आक्रामक है, इस प्रकार अधिक स्मृति बचाता है। Here you'll find a script जो अंतर प्रदर्शित करता है।
धन्यवाद! आपके समाधान और जो मैंने अभी जोड़ा है, वह चाल चल रहा है, मुझे उत्सुकता है कि आप और अन्य लोगों को लगता है कि एक बेहतर समाधान है। क्या आपके पास कोई विचार है? –
आपके समाधान कार्यों को चालू करता है और http://effbot.org/zone/element-iterparse.htm समाधान नहीं हुआ (यह अभी भी मेरी सभी मेमोरी खा चुका है) –
धन्यवाद! यह वह संस्करण है जो वास्तव में काम करता है। लिज़ा डेली, इफबॉट, और एलएक्सएमएल आधिकारिक दस्तावेज़ों के संस्करणों ने मेरे लिए बहुत मेमोरी नहीं बचाई। – fjsj