You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用configparser读取含$!的ini文件报错,如何解决?

问题描述

我的configs.ini文件中有如下配置项:

[app]
psw: Test123$!

使用以下Python代码读取时,触发configparser.InterpolationSyntaxError: '$' must be followed by '$' or '{', found: '$!'错误:

configs = configparser.RawConfigParser()
configs._interpolation = configparser.ExtendedInterpolation()
configs.read(configs_path)

print(configs.get('app', 'psw', fallback=''))

尝试用双美元符号(psw: Test123$$!)转义无效,现有资料多针对%字符的处理,请问如何正确读取含美元符号的ini配置?

解决方法

方法1:移除ExtendedInterpolation配置

你启用了ExtendedInterpolation,导致$被当作插值语法解析。如果不需要插值功能,直接移除插值设置即可——RawConfigParser默认不支持插值,不会解析$符号:

configs = configparser.RawConfigParser()
# 去掉这行:configs._interpolation = configparser.ExtendedInterpolation()
configs.read(configs_path)

print(configs.get('app', 'psw', fallback=''))

方法2:正确转义$(保留插值功能)

如果必须保留ExtendedInterpolation功能,需在ini文件中将单个$替换为$$转义:

[app]
psw: Test123$$!

保持原读取代码不变,读取后即可得到Test123$!。如果之前尝试转义无效,检查是否正确保存了ini文件,或者是否存在其他代码逻辑干扰。

方法3:禁用所有插值(Python 3.2+)

Python 3.2及以上版本中,可直接用ConfigParser并设置interpolation=None完全禁用插值,这样不管是%还是$都不会被解析:

configs = configparser.ConfigParser(interpolation=None)
configs.read(configs_path)

print(configs.get('app', 'psw', fallback=''))

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:12:12