限制Python多进程中的进程数量
我的需求是每秒生成数百个HTTP POST请求
。我现在是用urllib2
来实现这个。
def send():
req = urllib2.Request(url)
req.add_data(data)
response = urllib2.urlopen(req)
while datetime.datetime.now() <= ftime:
p=Process(target=send, args=[])
p.start()
time.sleep(0.001)
问题是这段代码在某些情况下有时会抛出以下异常
:
HTTP 503 Service Unavailable.
URLError: <urlopen error [Errno -2] Name or service not known>
我也尝试过使用requests(人性化的HTTP库)
,但在这个模块上遇到了一些代理问题。看起来requests
即使目标机器在同一个局域网内,也会把HTTP数据包发送到代理服务器。我不想让数据包经过代理服务器。
1 个回答
1
限制同时连接数量最简单的方法就是使用线程池:
#!/usr/bin/env python
from itertools import izip, repeat
from multiprocessing.dummy import Pool # use threads for I/O bound tasks
from urllib2 import urlopen
def fetch(url_data):
try:
return url_data[0], urlopen(*url_data).read(), None
except EnvironmentError as e:
return url_data[0], None, str(e)
if __name__=="__main__":
pool = Pool(20) # use 20 concurrent connections
params = izip(urls, repeat(data)) # use the same data for all urls
for url, content, error in pool.imap_unorderred(fetch, params):
if error is None:
print("done: %s: %d" % (url, len(content)))
else:
print("error: %s: %s" % (url, error))
503 Service Unavailable
是一种服务器错误。这意味着服务器可能无法处理当前的请求量。
Name or service not known
是一种DNS错误。如果你需要发送很多请求,可以考虑安装或启用一个本地的缓存DNS服务器。