![](/img/trans.png)
[英]Multiprocessing in Python while limiting the number of running processes
[英]Limiting number of processes in multiprocessing python
我的要求是hundreds of HTTP POST requests per second
生成hundreds of HTTP POST requests per second
。 我正在使用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)
問題在於此代碼sometimes for some iterations
拋出以下異常之一:
HTTP 503 Service Unavailable.
URLError: <urlopen error [Errno -2] Name or service not known>
我也嘗試過使用requests(HTTP for humans)
使用requests(HTTP for humans)
,但是該模塊存在一些代理問題。 似乎即使目標計算機在同一局域網內, requests
正在向代理服務器發送http數據包。 我不希望數據包進入代理服務器。
限制並發連接數的最簡單方法是使用線程池:
#!/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服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.