python之配置文件解析库configPasser、iniConfig
一、iniConfig
iniConfig 是一个轻量级的 INI 配置文件解析库,主要用于读取和解析 INI 格式的配置文件。
1、安装
pip install iniconfig
2、使用示例
[Database] host = localhost port = 3306 username = root password = 123456 [API] url = https://api.example.com key = your-api-key timeout = 30 [Settings] debug = true max_retries = 3
3、读取配置文件
from iniconfig import IniConfig
ini = IniConfig('config.ini')
4、读取单个值
db_host = ini.get('Database', 'host')
print(f"Database host: {db_host}")
# 或
value = ini['Database']['host']
5、读取某个部分,如database
for key in ini['Database']:
value = ini.get('Database', key)
print(f"{key}: {value}")
6、获取所有的section
sections = ini.sections
# 输出
{'Database': {'host': '192.168.1.111', 'port': '3306', 'username': 'root', 'password': '123456'}, 'API': {'url': 'https://api.example.com', 'key': 'your-api-key', 'timeout': '30'}, 'Settings': {'debug': 'true', 'max_retries': '3'}}
7、获取指定section的所有键
api_keys = list(ini['API'])
print("\nAPI section keys:", api_keys)
8、类型转化 在config.ini配置文件中常有数值或Boolean,需要转化
debug_mode = ini.get('Settings', 'debug') == 'true'
max_retries = int(ini.get('Settings', 'max_retries'))
print(f"\nDebug mode: {debug_mode}")
print(f"Max retries: {max_retries}")
二、configPasser
1、导入模块并读取配置文件
config.read() 支持多个文件名组成的列表。
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
2、获取字符串值(默认)
db_host = config['Database']['host']
api_url = config['API']['url']
print(db_host) # 输出: 192.168.1.111
print(api_url) # 输出: https://api.example.com
等价于
db_host = config.get('Database', 'host')
3、获取其他类型值(自动转换)
port = config.getint('Database', 'port') # int
timeout = config.getfloat('API', 'timeout') # float
debug = config.getboolean('Settings', 'debug') # bool
max_retries = config.getint('Settings', 'max_retries')
输出
port1 = config.getint('Database', 'port')
port2 = config.get('Database', 'port')
print(f"type port1: {type(port1)}")
print(f"type port2: {type(port2)}")
# 结果
type port1: <class 'int'>
type port2: <class 'str'>
4、判断配置项是否存在
if config.has_section('Database'):
if config.has_option('Database', 'username'):
user = config.get('Database', 'username')
5、遍历所有 Section 和 Option
for section in config.sections():
print(f"[{section}]")
for key, value in config.items(section):
print(f"{key} = {value}")
6、修改配置项
config.set('Settings', 'debug', 'false')
config.set('API', 'timeout', '60')
7、添加 Section 和 Option
if not config.has_section('Logging'):
config.add_section('Logging')
config.set('Logging', 'level', 'INFO')
with open('config.ini', 'w') as configfile:
config.write(configfile)
8、插值
支持默认值或引用其他项:
[DEFAULT]
base_url = https://api.example.com
[API]
endpoint = %(base_url)s/v1/data
# 访问
endpoint = config.get('API', 'endpoint') # 自动替换为 https://api.example.com/v1/data
9、注意事项
所有返回值默认为 字符串,除非使用 getint(), getfloat(), getboolean()。
configparser 区分大小写的值(值保留大小写),但 section 和 key 默认转为小写。
可通过修改:
config = configparser.ConfigParser() config.optionxform = str # 保留 key 的大小写
三、configPasser 和 iniconfig的对比
iniconfig 和 configparser 都是用于处理 .ini 配置文件的 Python 模块,但它们在设计理念、功能范围、使用场景等方面存在一些区别。以下是它们的详细对比:
1、基本介绍
| 特性 | configparser | iniconfig |
|---|---|---|
| 所属库 | Python 标准库,自 Python 3 起内置 | 第三方库,需使用 pip install iniconfig |
| 设计目的 | 通用 .ini 配置文件解析器 |
简洁、安全,主要用于 pytest 插件配置等场景 |
| 文件格式支持 | .ini(支持 sections/keys/values) |
.ini(强调简单语法,避免复杂解析) |
2、语法支持对比
| 功能项 | configparser | iniconfig |
|---|---|---|
| Section 支持 | ✅ | ✅ |
| Key-Value 支持 | ✅ | ✅ |
注释解析(; 和 #) |
✅ | ✅ |
| 多行值 | ✅(通过 indentation) |
❌(不支持) |
| 插值(变量替换) | ✅ | ❌ |
| 类型转换 | ✅(如 getint, getboolean) |
❌(值都是字符串) |
| 写入配置文件 | ✅(支持 write()) |
❌(只读) |
3、使用场景对比
| 场景 | 建议使用模块 | 理由 |
|---|---|---|
| 通用配置解析 | configparser |
功能更全面,支持类型转换、多行、写入等 |
简单读取 .ini 配置,无需写入 |
iniconfig |
更简洁,零依赖,适用于只读场景 |
| 用于 pytest 插件或配置 | iniconfig |
是 pytest 官方推荐使用的配置解析器之一 |
| 需要处理复杂配置和插值 | configparser |
功能更强,支持 %() 插值语法和更多配置选项 |

浙公网安备 33010602011771号