使用loguru将列表写回配置文件,并收到可怕的unsupported operand type(s) for +: 'NoneType' and 'list'
错误。我知道错误来自试图组合一个文字和一个列表。我试图通过使用一个变量来表示文字来分解这一行,这只会产生同样的错误。
带有问题行的代码块:
def update_config(config: dict):
"""
Update exisitng configuration file.
Parameters
----------
config: dict
Configuraiton to be written into config file.
"""
config["ids_to_retry"] = list(set(config["ids_to_retry"] + FAILED_IDS))
with open("config.yaml", "w") as yaml_file:
yaml.dump(config, yaml_file, default_flow_style=False)
logger.info("Updated last read message_id to config file")
全错误输出:
Traceback (most recent call last):
File "/telegram-downloader-quackified/media_downloader.py", line 359, in <module>
main()
File "/telegram-downloader-quackified/media_downloader.py", line 343, in main
updated_config = asyncio.get_event_loop().run_until_complete(
File "/miniconda3/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/telegram-downloader-quackified/media_downloader.py", line 324, in begin_import
update_config(config)
File "/telegram-downloader-quackified/media_downloader.py", line 35, in update_config
config["ids_to_retry"] = list(set(config["ids_to_retry"] + FAILED_IDS))
我知道list(set(config["ids_to_retry"] + FAILED_IDS))
这个短语需要改变,我只是不确定是什么。
提供更多信息:
FAILED_IDS是脚本遇到异常但无法成功完成下载时生成的列表。当发生这种情况时,消息id将像FAILED_IDS.append(message.message_id)
一样存储在内存中。然后用以下语句将其写入配置文件:
if FAILED_IDS:
logger.info(
"Downloading of %d files failed. "
"Failed message ids are added to config file.\n",
len(set(FAILED_IDS)),
)
update_config(updated_config)
它的原始价值是:
FAILED_IDS: list = []
其中"ids_to_retry“或多或少只是配置文件中使用的标签。它只是一个文字字符串,是非类型的。最终的结果是将两者写入配置文件中,类似于如下所示:
ids_to_retry:
- 26125
- 2063
- 2065
- 2080
- 2081
- 22052
- 21029
- 553
- 554
- 555
- 2102
- 22074
我希望这澄清了我们正在处理的变量的性质。
发布于 2021-05-11 06:39:16
失败的原因是config["ids_to_retry"] = None
,您正在尝试将Nonetype扩展到列表中。你可以用这样的方法
config["ids_to_retry"] = list(set(config["ids_to_retry"] + FAILED_IDS)) if config["ids_to_retry"] else FAILED_IDS
因此,如果config["ids_to_retry"]
是None
,它将采用config["ids_to_retry"] = FAILED_IDS
,而无需尝试扩展它。
假设FAILED_IDS
是一个列表,如果不能,可以将它键入到列表中。
https://stackoverflow.com/questions/67481542
复制相似问题