我有一個刮板(基於Python 3.4.2和asyncio/aiohttp庫)和一堆鏈接(> 10K)來檢索一些少量的數據。刮板代碼 部分:未來的例外從未檢索
@asyncio.coroutine
def prepare(self, links):
semaphore = asyncio.Semaphore(self.limit_concurrent)
tasks = []
result = []
tasks = [self.request_data(link, semaphore) for link in links]
for task in asyncio.as_completed(tasks):
response = yield from task
if response:
result.append(response)
task.close()
return result
@asyncio.coroutine
def request_data(self, link, semaphore):
...
with (yield from semaphore):
while True:
counter += 1
if counter >= self.retry:
break
with aiohttp.Timeout(self.timeout):
try:
response = yield from self.session.get(url, headers=self.headers)
body = yield from response.read()
break
except asyncio.TimeoutError as err:
logging.warning('Timeout error getting {0}'.format(url))
return None
except Exception:
return None
...
煥它試圖使請求URL格式不正確的,我得到的消息是這樣的:
Future exception was never retrieved
future: <Future finished exception=gaierror(11004, 'getaddrinfo failed')>
Traceback (most recent call last):
File "H:\Python_3_4_2\lib\concurrent\futures\thread.py", line 54, in run
result = self.fn(*self.args, **self.kwargs)
File "H:\Python_3_4_2\lib\socket.py", line 530, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
試圖收益率從session.get響應時使用錯誤occures。據我瞭解,異常從未被asyncio消耗,所以它不是「喋喋不休」。
首先我tryed簡單地通過試/包請求,除非:
try:
response = yield from self.session.get(url, headers=self.headers)
except Exception:
return None
這是行不通的。
然後我關於鏈接協程來捕捉異常,但這並不適用於我。在一段時間後,我仍然會收到這些消息和腳本崩潰。
所以我的問題 - 我如何能以適當的方式處理這個異常?
是的,我期待着那個方向,但還有其他問題。小型研究表明,並非所有鏈接都會導致此錯誤格式不正確。其中一些只有重定向或WebSocket的服務器而不是http(s)。我認爲在這種情況下最好能夠發現異常。 – Charnel
也許你可以通過這裏討論的方法發佈調試追蹤: https://docs.python.org/3/library/asyncio-dev.html#detect-exceptions-never-consumed 也許它會提供更多的信息究竟是什麼觸發它。 無論哪種方式好運,刮板可以是一個噩夢來維持和保持運行^^ – user7296055