config.ini文件读取URL失败,配置文件中的值包含特殊字符(例如 %),可能导致解释错误
原来的代码:
import configparser
import os.path
from urllib.parse import quote, unquote
config1 = configparser.ConfigParser()
config_path = os.path.abspath(os.path.dirname(__file__))[:os.path.abspath(os.path.dirname(__file__))
.find("Project")+len("Project")]+"/config/config.ini"
config1.read(config_path)
special_value1 = config1.get('host', 'Project_address')
special_value12 = config1.get('host', 'url')
报错提示:
```python
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%3A%2F%2F192.168.98.xxxx%3ACCCC9%2Fsmart%2F%23%2Flogin'
报错原因
configparser.ConfigParser():
默认情况下,configparser.ConfigParser() 会对配置文件中的值进行插值(interpolation)处理。这意味着它会尝试解释配置文件中的值,替换变量,并执行特定的替换操作。
适用于大多数情况,但在某些情况下,如果配置文件中的值包含特殊字符(例如 %),它可能导致解释错误。
解决方案
使用 configparser.RawConfigParser() 这个参数替换 configparser.ConfigParser():
configparser.RawConfigParser():
configparser.RawConfigParser() 不执行值的插值,它将值视为纯文本,不会尝试解释或替换它们。
适用于需要保留配置文件中值的原始形式的情况,包括特殊字符。
代码如下:
config1 = configparser.RawConfigParser()
config_path = os.path.abspath(os.path.dirname(__file__))[:os.path.abspath(os.path.dirname(__file__))
.find("Project")+len("Project")]+"/config/config.ini"
config1.read(config_path)
special_value1 = config1.get('host', 'Project_address')
special_value12 = config1.get('host', 'url')
运行成功 成功读取 url 跟 Project_address
对于初学者来说直接替换即可
欢迎大家评价有更新更好的方法进行编写!