python-3.x - asyncio 抛出运行时错误并忽略异常
问题描述
下面是一个收集 URL 长度的简单程序。
import aiohttp
import asyncio
from time import perf_counter
URLS = ['http://www.cnn.com', 'http://www.huffpost.com', 'http://europe.wsj.com',
'http://www.bbc.co.uk', 'http://failfailfail.com']
async def async_load_url(url, session):
try:
async with session.get(url) as resp:
content = await resp.read()
print(f"{url!r} is {len(content)} bytes")
except IOError:
print(f"failed to load {url}")
async def main():
async with aiohttp.ClientSession() as session:
tasks = [async_load_url(url, session) for url in URLS]
await asyncio.wait(tasks)
if __name__ == "__main__":
start = perf_counter()
asyncio.run(main())
elapsed = perf_counter() - start
print(f"\nTook {elapsed} seconds")
为什么以下代码因运行时错误而失败,python 3.9 中忽略了异常?如何解决?
Traceback 是:RuntimeError: Event loop is closed
特别是与Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001F8A7A713A0>
解决方案
This is caused by a known issue in aiohttp on Windows, for details check out the bug at https://github.com/aio-libs/aiohttp/issues/4324
There are a couple of hacks that silence this error. The first way is to get the event loop and call run_until_complete
instead of asyncio.run(main())
like so:
asyncio.get_event_loop().run_until_complete(main())
Alternatively, changing the event loop policy to WindowsSelectorEventLoopPolicy
before calling asyncio.run(main())
also works as the problem seems to occur when using WindowsProtractorEventLoopPolicy
.
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Of course, the second solution will make your code platform specific, so be careful.
推荐阅读
- node.js - 没有为 null 类型定义协议方法 IDeref.-deref
- reactjs - docker 程序未检测到卷更改
- flutter - Flutter OnTap Listview 项
- javascript - Javascript innerHTML 被自动覆盖并失效
- jenkins-pipeline - 在 Jenkins-Openshift 容器中执行 Cypress 测试
- html - 尝试在 CSS 中的下拉选择中更改悬停时的选项背景颜色
- ios - iPad 在多任务处理 Slide Over (SwiftUI/UIKit) 中的键盘安全区域错误
- java - Spring @Value 总是导致 `null`
- javascript - 获取在 Chrome 中查看的本地 PDF 的最左侧 x 坐标
- deployment - 尝试通过 Jenkins 部署时,外部字符串不存在错误