【问题标题】:My code keeps getting killed for memory issues我的代码因内存问题而不断被杀死
【发布时间】:2015-06-30 15:06:32
【问题描述】:

所以我编写了这个脚本来检查一个大型 wiki XML 转储并提取我想要的页面。但是,每次我运行它时,内核都会显示“Killed”,我在阅读后假设这是一个内存问题,但我不确定我的脚本中的内存问题在哪里,以及是否有任何技巧可以减少虚拟内存用法。

这是我的代码(我认为问题出在 BeautifulSoup 分区中,因为页面文件非常小。

from bs4 import BeautifulSoup
import sys

pages_file = open('pages_file.txt', 'r')

#Preprocessing
pages = pages_file.readlines()
pages = map(lambda s: s.strip(), pages)
page_titles=[]
for item in pages:
  item = ''.join([i for i in item if not i.isdigit()])
  item = ''.join([i for i in item if ord(i)<126 and ord(i)>31])
  item = item.replace(" ","")
  item = item.replace("_"," ")
  page_titles.append(item)


with open(sys.argv[1], 'r') as wiki:    
  soup = BeautifulSoup(wiki)
wiki.closed
wiki_page = soup.find_all("page")
del soup
for item in wiki_page:
  title = item.title.get_text()
  if title in page_titles:
      print item
  del title

【问题讨论】:

  • 这是我得到的 dmesg 错误 [15206379.618471] 内存不足:杀死进程 16548(python)得分 465 或牺牲孩子 [15206379.620207] 杀死进程 16548(python)total-vm:52133996kB,anon- rss:50032968kB,文件-rss:0kB

标签: shell memory-leaks beautifulsoup out-of-memory


【解决方案1】:

如果 XML 文件很大,您可以使用 Soup Strainer 来处理它。请参阅http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-only-part-of-a-document 上的文档。在您的情况下,您可以简单地搜索title 标签,因为您根据列表检查每个标签。

请注意,您不需要像那样使用“del”语句,但我想您这样做是为了解决错误?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多