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

相关推荐
Flittly7 分钟前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling4 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook8 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风9 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风9 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm