【问题标题】:urllib or json memory leak python 3urllib 或 json 内存泄漏 python 3
【发布时间】:2017-10-26 19:15:31
【问题描述】:

我想从 url 获取和使用数据,然后重复一个循环。 当我运行代码时,我的操作内存使用量 (MacOS) 会随着每个循环而增加。我怎样才能防止这种情况发生?

提前谢谢你!

import urllib.request, json 
import time
import resource
import gc
import contextlib

def bb():
    try:        
        with contextlib.closing(urllib.request.urlopen("https://bitbay.net/API/Public/ETHPLN/ticker.json")) as url:
        data = json.loads(url.read().decode())

        ## do something with data

        del data
        gc.collect()

    except urllib.error.HTTPError as err:
        pass


def resident_memory() -> int:
    return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss


x = 0
while x == 0:
    bb()
    print('Mem usage:', resident_memory())
    time.sleep(1)

【问题讨论】:

  • 我做了一些实验,罪魁祸首不是json也不是底层socket,而是urllib内部,需要更多时间才能找出来。
  • 谢谢。我希望你能解决它!

标签: python json python-3.x memory-leaks urllib


【解决方案1】:

我在 Python 3.7.4 中遇到了同样的问题。我最终切换到 urllib3 (https://urllib3.readthedocs.io/en/latest/),问题立即消失了。另外,我将我的 HTTP PoolManager 放在了循环范围之外。

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 2011-12-13
    • 2014-02-26
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2010-11-17
    相关资源
    最近更新 更多