python3 asyncio 协程关闭问题,谢谢大家,搞的烦死了~
以下是代码一运行就报错:RuntimeError: Event loop is closed网上找了很多资料的解决方法也都不行,请问哪里的问题?谢谢大家
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import asyncio
import aiohttp
URL = 'https://www.xiazaiba.com'
async def job(session):
response = await session.get(URL)
return str(response.url)
async def main(loop):
async with aiohttp.ClientSession() as session:
tasks = [loop.create_task(job(session)) for _ in range(5)]
finished, unfinished = await asyncio.wait(tasks)
all_results = [r.result() for r in finished] # 得到工作回报.
print(all_results)
if __name__ == '__main__':
t2 = time.time()
loop = asyncio.get_event_loop() # 创建一个事件循环对象loop
try:
loop.run_until_complete(main(loop)) # 完成事件循环,直到最后一个任务结束
finally:
loop.close() # 结束事件循环.
print("Async total time:", time.time() - t2)
推荐文章: