对比
格式 | 优点 | 缺点 | 是否支持注释 |
---|---|---|---|
INI | 简单易懂 语言内置支持 | 不支持复杂数据结构 | ✓ |
JSON | 支持复杂数据结构 | 阅读起来不够直观 | × |
YAML | 简洁有序 支持复杂数据结构 | 灵活但有歧义 不同实现有兼容性问题 | ✓ |
XML | 支持复杂数据结构和命名空间 | 语法冗长体积较大 | ✓ |
TOML | 语法简洁 支持复杂数据结构 | 相对较新 | ✓ |
INI
键值分隔符为 =
或 :
注释符为 #
或 ;
缺乏统一的标准,不能表示复杂数据结构,常用于 Windows 程序
config.ini
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true
[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day
[No Values]
key_without_value
empty string value here =
[You can use comments]
# like this
; or this
# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.
[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?
import configparser
config = configparser.ConfigParser(allow_no_value=True)
config.read('config.ini', encoding='utf-8')
for section in config.sections():
print(section)
for key, value in config.items(section):
print(' {} = {}'.format(key, value))
特殊字符如 %
会报错 configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%xxxx'
可以用 %%
或者 config.get('MYSQL', 'PASSWORD', raw=True)
JSON
常用于 JavaScript、Python、Node.js、Ruby
config.json
{
"mysql": {
"host": "127.0.0.1",
"user": "root",
"password": "123456",
"port": 3306,
"database": "mysql"
}
}
import json
config = json.load(open('config.json'))
print(config)
YAML
注释符为 #
常用于 Python、Java、Go 等
config.yaml
language: python
mysql:
host: localhost
port: 3306
username: user
password: secret
fields:
- id
- name
- age
安装
pip install PyYAML
import yaml
config = yaml.safe_load(open('config.yaml', 'r', encoding='utf-8'))
print(config)
XML
注释符为 <!--
结合 -->
常用于 Java、C#、.NET、Scala 等
<config>
<database>
<host>localhost</host>
<port>3306</port>
<username>user</username>
<password>secret</password>
</database>
</config>
import xml.etree.ElementTree as ET
tree = ET.parse('config.xml')
root = tree.getroot()
config = {}
for child in root:
config[child.tag] = {subchild.tag: subchild.text for subchild in child}
print(config)
TOML
注释符为 #
常用于 Python、Rust、Go 等
config.toml
# This is a TOML document
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
[database]
enabled = true
ports = [ 8000, 8001, 8002 ]
data = [ ["delta", "phi"], [3.14] ]
temp_targets = { cpu = 79.5, case = 72.0 }
[servers]
[servers.alpha]
ip = "10.0.0.1"
role = "frontend"
[servers.beta]
ip = "10.0.0.2"
role = "backend"
Python 3.11 标准库开始有 tomllib
import tomllib
config = tomllib.load(open('config.toml', 'rb'))
print(config)
其余版本使用 toml
pip install toml
import toml
config = toml.load(open('config.toml', 'r'))
print(config)
python-dotenv
从 .env 文件中读取键值对,并将它们设置为环境变量,有助于遵循云原生开发十二要素
安装
pip install python-dotenv
.env
DB_HOST=localhost
DB_PORT=5432
DB_USER=admin
DB_PASSWORD=secretpassword
API_KEY=your_api_key_here
读取
import os
from dotenv import load_dotenv
load_dotenv(override=True)
print(os.getenv('DB_HOST'))
写入
from dotenv import dotenv_values, set_key, find_dotenv
config = dotenv_values()
dotenv_path = find_dotenv()
config['DB_PASSWORD'] = '123456'
for key, value in config.items():
set_key(dotenv_path, key, value)