【问题标题】:Too many open files when using requests package python使用请求包python时打开的文件太多
【发布时间】:2019-03-18 21:53:22
【问题描述】:

我正在使用 Python requests 包向 API 发出大量请求。然而,在某些时候,我的程序由于“打开的文件太多”而崩溃。当我明确地关闭我的会话时,我真的不知道这是怎么回事。

我使用以下代码:

import requests
import multiprocessing
import numpy as np

s = requests.session()
s.keep_alive = False


def request(i, mapId, minx, maxx, miny, maxy):
    print(i)
    try:
        with requests.Session() as s:
            r = s.post(
                url + "metadata/polygons",
                timeout=10,
                json={
                    "mapId": mapId,
                    "layer": "percelen",
                    "xMin": minx,
                    "xMax": maxx,
                    "yMin": miny,
                    "yMax": maxy,
                },
            )
            out = r.json()
            s.close()

    except:
        print("something went wrong with: " + str(i))


for i in np.aragne(10000):
    time.sleep(1)
    multiprocessing.Process(target=request, args=argsList[i])

任何帮助或见解将不胜感激,因为我没有想法。

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    “打开的文件太多”可能是指每个 Session 及其单个 POST 请求占用一个 TCP 套接字,因此占用一个文件描述符。

    第一个解决方案:

    将单个Session 实例与a customized HTTPAdapter 一起使用,并将增强的参数传递给它的pool_connections 参数。

    附注 1:您无需致电 s.close()。当上下文管理器调用 .__exit__() 时,它已经被调用了。

    旁注 2:考虑使用threadingasyncio/aiohttp。对于这样的 IO 密集型任务,多处理并不理想。

    第二种解决方案:

    增加允许打开的文件数。在 Linux 上,您需要执行以下操作:

    sudo vim /etc/security/limits.conf
    # Add these lines
    root    soft    nofile  100000
    root    hard    nofile  100000
    ubuntu    soft    nofile  100000
    ubuntu    hard    nofile  100000
    
    sudo vim /etc/sysctl.conf
    # Add this line
    fs.file-max = 2097152
    
    sudo sysctl -p
    
    sudo vim /etc/pam.d/commmon_session
    # Add this line
    session required pam_limits.so
    
    sudo reboot
    

    我认为第二种解决方案可以被描述为“解决症状而不是问题”,但如果你必须尝试并且感觉大胆,请尝试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2017-10-09
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多