使用请求包python时打开的文件太多

时间:2019-03-18 21:53:22

标签: python python-requests

我正在使用Python请求包向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])

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

1 个答案:

答案 0 :(得分:2)

“打开的文件太多”可能是由于每个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

我认为第二种解决方案的特征可以是“解决症状而不是解决问题”,但是如果您必须并且感到胆大的话,可以尝试一下。