【问题标题】:Python Script with Gevent Pool, consumes a lot of memory, locks up带有 Gevent 池的 Python 脚本,消耗大量内存,锁定
【发布时间】:2013-06-10 04:59:19
【问题描述】:

我有一个非常简单的 Python 脚本,它使用 gevent.pool 下载 URL(见下文)。该脚本运行了几天,然后锁定。我注意到当时内存使用率非常高。我是否错误地使用了 gevent?

import sys

from gevent import monkey
monkey.patch_all()
import urllib2

from gevent.pool import Pool

inputFile = open(sys.argv[1], 'r')
urls = []
counter = 0
for line in inputFile:
    counter += 1
    urls.append(line.strip())
inputFile.close()

outputDirectory = sys.argv[2]

def fetch(url):
    try:
        body = urllib2.urlopen("http://" + url, None, 5).read()
        if len(body) > 0:
            outputFile = open(outputDirectory + "/" + url, 'w')
            outputFile.write(body)
            outputFile.close()
            print "Success", url
    except:
        pass

pool = Pool(int(sys.argv[3]))
pool.map(fetch, urls)

【问题讨论】:

  • 听起来像是gevent 中的内存泄漏。快速搜索python gevent memory leak 会返回惊人的大量点击,尽管您可能更容易确定其中任何一个是否适用于您的特定情况。

标签: python python-2.7 gevent


【解决方案1】:
        body = urllib2.urlopen("http://" + url, None, 5).read()

上面一行将内存中的全部内容作为字符串读取。为防止这种情况发生,请按如下方式更改 fetch():

def fetch(url):
    try:
        u = urllib2.urlopen("http://" + url, None, 5)
        try:
            with open(outputDirectory + "/" + url, 'w') as outputFile:
                while True:
                    chunk = u.read(65536)
                    if not chunk:
                        break
                    outputFile.write(chunk)
        finally:
            u.close()
        print "Success", url
    except:
        print "Fail", url

【讨论】:

  • 用 open(... ) 作为 outputFile ... 而不是 try
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多