我写了这个简单的代码来使用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)
它正常工作。可以使用此选项吗?为什么会这样?