修改例程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()就好了。

相关推荐
markfeng89 分钟前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤2 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean2 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽3 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188964 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听5 小时前
RAG深入学习之Chunk
前端·人工智能·python
用户8356290780516 小时前
自动化文档处理:Python 批量提取 PDF 图片
后端·python