[英]Python: Aioimaplib catch exceptions
我試圖與aioimaplib異步檢查多個imap登錄信息。 只要imap服務器可訪問和/或客戶端不超時,此代碼就起作用。
捕獲異常的正確方法是什么?
示例異常:
ERROR:asyncio:Task exception was never retrieved future: <Task finished coro=<BaseEventLoop.create_connection() done, defined at G:\WinPython-3.5.4\python-3.5.4.amd64\lib\asyncio\base_events.py:679> exception=TimeoutError(10060, "Connect call failed ('74.117.114.100', 993)")>
碼:
account_infos = [
# User Password Server
('user1@web.com', 'password1', 'imap.google.com'),
('user2@web.com', 'password2', 'imap.yandex.com'),
('user3@web.com', 'password3', 'imap.server3.com'),
]
class MailLogin:
def __init__(self):
self.loop = asyncio.get_event_loop()
self.queue = asyncio.Queue(loop=self.loop)
self.max_workers = 2
async def produce_work(self):
for i in account_infos:
await self.queue.put(i)
for _ in range(max_workers):
await self.queue.put((None, None, None))
async def worker(self):
while True:
(username, password, server) = await self.queue.get()
if username is None:
break
while True:
try:
s = IMAP4_SSL(server)
await s.wait_hello_from_server()
r = await s.login(username, password)
await s.logout()
if r.result != 'NO':
print('Information works')
except Exception as e:
# DOES NOT CATCH
print(str(e))
else:
break
def start(self):
try:
self.loop.run_until_complete(
asyncio.gather(self.produce_work(), *[self.worker() for _ in range(self.max_workers)],
loop=self.loop, return_exceptions=True)
)
finally:
print('Done')
if __name__ == '__main__':
MailLogin().start()
有幾種方法可以執行此操作,但您的except
可能捕獲了TimeoutError
。 您看不到它,因為str(e)是一個空字符串。
首先,您可以像以前那樣捕獲異常:
async def fail_fun():
try:
imap_client = aioimaplib.IMAP4_SSL(host='foo', timeout=1)
await imap_client.wait_hello_from_server()
except Exception as e:
print('Exception : ' + str(e))
if __name__ == '__main__':
get_event_loop().run_until_complete(fail_fun())
其次,您可以在run_until_complete
處捕獲異常
async def fail_fun():
imap_client = aioimaplib.IMAP4_SSL(host='foo', timeout=1)
await imap_client.wait_hello_from_server()
if __name__ == '__main__':
try:
get_event_loop().run_until_complete(fail_fun())
except Exception as e:
print('Exception : ' + str(e))
建立連接,將loop.create_connection
協程與create_task
包裹在一起:我們想在IMAP4構造函數中建立連接,並且__init__
應該返回None 。
因此,如果主機的值錯誤,則可以在之前對其進行測試,或者等待超時:
socket.gaierror: [Errno -5] No address associated with hostname
如果主機在超時之前沒有響應,則可以提高超時時間。 而且,如果在連接過程中連接丟失,則可以在IMAP4構造函數中添加連接丟失回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.