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

相关推荐
喵手5 小时前
Python爬虫实战:构建“时光机”——网站数据增量监控与差异分析系统!
爬虫·python·爬虫实战·差异分析·零基础python爬虫教学·网站数据增量·网站数据增量监控系统
Katecat996635 小时前
SAR图像火情与烟雾检测:Cascade-Mask-RCNN与RegNetX模型融合详解
python
禁默5 小时前
零基础全面掌握层次分析法(AHP):Python实现+论文加分全攻略
python·数学建模·matlab
深蓝电商API5 小时前
爬虫数据导出 Excel:openpyxl 高级用法
爬虫·python·openpyxl
reasonsummer5 小时前
【教学类-74-05】20260216剪影马(黑色填充图案转黑线条白填充)
python
查士丁尼·绵6 小时前
通过sdk获取ecs指标
python·sdk
喵手6 小时前
Python爬虫实战:失败重试分级 - DNS/超时/403 分策略处理 + 重试退避等!
爬虫·python·爬虫实战·零基础python爬虫教学·失败重试分级·dns/超时·重试退避
得一录6 小时前
Python 算法高级篇:布谷鸟哈希算法与分布式哈希表
python·算法·aigc·哈希算法
Faker66363aaa6 小时前
基于Cascade-Mask-RCNN和RegNetX-4GF的果蝇检测与识别系统——COCO数据集训练与优化
python
聂 可 以6 小时前
解决Pycharm中(Python)软件包下载速度很慢、甚至下载失败的问题
ide·python·pycharm