python-3.x - Windows 上的“RuntimeError:事件循环已关闭”
问题描述
我编写了这个简单的代码来使用 asyncio 和 aiohttp 获取一些 url。
import asyncio
import aiohttp
async def fetch(url, session):
async with session.get(url) as response:
return await response.read()
async def fetch_all(urls):
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
task = asyncio.create_task(fetch(url, session))
tasks.append(task)
return await asyncio.gather(*tasks)
if __name__ == '__main__':
res = asyncio.run(fetch_all(['http://www.youtube.com', 'http://www.google.com']))
print(res)
我正在使用 Python 3.8 和 PyCharm,它在 MacOS 上运行良好。如果我尝试在 Windows 上运行它,它仍然可以工作,但是在打印结果后,它给了我
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x036ED2B0>
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files (x86)\Python38-32\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Program Files (x86)\Python38-32\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
但是,如果我替换asyncio.run()
为
loop = asyncio.get_event_loop()
res = loop.run_until_complete(fetch_all(['http://www.youtube.com', 'http://www.google.com']))
print(res)
它可以正常工作。可以使用这个选项吗?为什么会这样?
解决方案
推荐阅读
- angular - 将所有页面中的默认文本替换为自定义文本
- python - PythonAnywhere:SystemError:参数说明符多于关键字列表条目(剩余格式:'s#|O!O!O!')
- java - 在 JavaFX TreeView 中手动提交编辑
- java - 为什么 Roy 和头像hackerearth 的测试用例失败了?
- google-calendar-api - Google 日历 - 外部活动来宾的自动电子邮件通知
- html - 我应该使用 role="note" 作为输入的帮助文本吗?
- javascript - 问题循环遍历数组
- arrays - for 循环弄乱数组返回
- go - 如何回复频道的发送者并管理状态
- python - Python 从 Gcloud 获取账单信息