修改例程flags3_asyncio.py以解决RuntimeError错误

运行示例18-13 flags3_asyncio.py,程序报错如下:

D:\Python\Python311\python.exe D:\fluentPy\chapter17_18\flags3_asyncio.py

REMOTE site: https://www.fluentpython.com/data/flags/

Searching for 20 flags: from BD to VN

5 concurrent connections will be used.

100%|██████████| 20/20 [00:07<00:00, 2.61it/s]


20 flags downloaded.

Elapsed time: 7.70s

exception calling callback for <Future at 0x1bc2da71b90 state=finished returned NoneType>

Traceback (most recent call last):

......

raise RuntimeError('Event loop is closed')

RuntimeError: Event loop is closed

进程已结束,退出代码为 0

很奇怪,明明下载成功了,但是最后还是出现错误提示,经过检查,发现问题出在函数

async def download_one(cc, base_url, semaphore, verbose):

try:

async with semaphore:

image = await get_flag(base_url, cc)

async with semaphore:

country = await get_country(base_url, cc)

except web.HTTPNotFound:

status = HTTPStatus.not_found

msg = 'not found'

except Exception as exc:

raise FetchError(cc) from exc

else:

country = country.replace(' ', '_')

filename = '{}-{}.gif'.format(country, cc)

loop = asyncio.get_event_loop()

loop.run_in_executor(None, save_flag, image, filename)

status = HTTPStatus.ok

msg = 'OK'

if verbose and msg:

print(cc, msg)

return Result(status, cc)

里,只要把loop = asyncio.get_event_loop()改成loop = asyncio.new_event_loop()就好了。

相关推荐
读研的武2 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy2 小时前
Python基础语法4
开发语言·python
mm-q29152227293 小时前
Python+Requests零基础系统掌握接口自动化测试
开发语言·python
电院工程师4 小时前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
Python图像识别5 小时前
75_基于深度学习的咖啡叶片病害检测系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
闲人编程5 小时前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
雍凉明月夜6 小时前
人工智能学习中深度学习之python基础之 类
python·学习
Geo_V6 小时前
OpenAI 大模型 API 使用示例
python·chatgpt·openai·大模型应用·llm 开发
Hello_WOAIAI6 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python