本文主要是介绍修改例程flags_asyncio.py使能在python311环境下运行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先贴上修改后的例程:
import asyncio
import aiohttp
import time
from flags import BASE_URL, save_flag, show, POP20_CC
async def get_flag(cc):
async with aiohttp.ClientSession() as session:
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
async with session.get(url) as response:
image = await response.read()
return image
async def download_one(cc):
image = await get_flag(cc)
show(cc)
save_flag(image, cc.lower() + '.gif')
return cc
async def download_many(cc_list):
# loop = asyncio.new_event_loop()
tasks = [asyncio.create_task(download_one(cc)) for cc in cc_list]
wait_coro, pending = await asyncio.wait(tasks)
# res = loop.run_until_complete(wait_coro)
# loop.close()
return len(wait_coro)
def main(download_many, cc_list):
t0 = time.time()
count = asyncio.run(download_many(cc_list))
elapsed = time.time() - t0
msg = '\n{} flags downloaded in {:.2f}s'
print(msg.format(count, elapsed))
if __name__ == '__main__':
main(download_many, POP20_CC)
修改之处主要有三处:
1,在get_flag函数内使用
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
替换原来的:
yield from aiohttp.request('GET', url)
2,在download_many函数内弃用loop,直接用asyncio.create_task生成Future迭代器传给asyncio.wait函数
3,在main函数里使用asyncio.run函数调用download_many函数
最后贴上例程运行输出:
C:\Users\fange\Scripts\python.exe D:\fluentPy\chapter17_18\flags_asyncio.py
IN CN BR PK US ET VN BD CD FR JP DE PH ID EG NG RU IR TR MX
20 flags downloaded in 10.55s
进程已结束,退出代码为 0
这篇关于修改例程flags_asyncio.py使能在python311环境下运行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!