我正在经历一个可怕的内存泄漏的情况。我用beutifulsoup创建一个对象,然后通过它自己的方法处理它。我用~2000个XML文件来做这个。在处理了大约一半后,程序由于内存错误而停止工作,性能不断下降。我试图通过汤。分解对__del__
和强制gc.收集处理完每个文件后。在
class FloorSoup:
def __init__(self, f_id):
only_needed = SoupStrainer(["beacons", 'hint'])
try:
self.f_soup = BeautifulSoup(open("Data/xmls/floors/floors_" + f_id + ".xml", encoding='utf8'), "lxml", parse_only = only_needed)
except (FileNotFoundError):
print("File: Data/xmls/floors/floors_" + f_id + ".xml not found")
def __del__(self):
self.f_soup.decompose()
def find_floor_npcs(self):
found_npcs = set()
for npc in self.f_soup.find_all(text="npc"):
found_npcs.add(npc.parent.parent.values.string)
return found_npcs
def find_floor_hints(self):
hint_ids = set()
print("Finding hints in file")
for hint in self.f_soup.find_all('hint'):
hint_ids.add(hint.localization.string)
return hint_ids
我用来创建对象和调用方法的代码的相关部分:
^{pr2}$通过停止使用find_floor_hints方法,我几乎可以完全消除内存泄漏(或者达到其影响可以忽略不计的程度)。因此,我怀疑问题可能出在那个特定的方法上。在
任何帮助将不胜感激!在
引用this answer,我可以使用
前者似乎返回了一个可导航的字符串,即使在floorGroup对象被删除之后,也会留下一些(读:非常多)引用。我不太确定这是一个bug还是一个特性,但它是有效的。在
相关问题 更多 >
编程相关推荐