配置文件 config.toml
#这是一个Toml 示例:
[mysql]
host = "localhost"
user = "root"
port = 3306
database = "an"
password = "jiang"
[mysql.parameters]
pool_size = 5
charset = "utf8"
[mysql.fields]
pandas_cols = [ "id", "name", "age", "date"]
[head] #[]内不能有汉字
title = "TOML Example标题" #可是双括号,可有汉字
subject = 'subject标题 Example' #可是单括号,可有汉字
汉字标题subject = '标题 Example' #key可有汉字,value可有汉字
[owner]
name = "Tom Preston-Werner演示"
dob =1979-05-27T07:32:00-08:00 #能识别的datetime.datetime类型
dob2 =2022-12-03T09:32:01 #能识别的datetime.datetime类型
dob3 =2022-12-03 09:32:01 #能识别的datetime.datetime类型
dob4 =2022-12-03 #能识别的datetime.date类型
[database]
enabled = true #true要小写,不能checked = True
ports =[ 8000,8001,8002 ]
data = [ ["delta",'phi'],[3.14,0.618]] #[3.14,0.618]必须是同类;[3.14,0.618,5]报错
temp_targets = { cpu = 79.5,case =72.0 }
[servers]
alias='sample1'
[servers.alpha] #字典内的字典dict['servers']['alpha']
ip = "10.0.0.1"
role = "frontend"
[servers.beta]
ip ="10.0.0.2" #缩进不做要求
role = "backend"
代码简单
import toml #pip install toml
cfg=toml.load('config.toml')
print(cfg)
print('\n第2部分')
print(cfg['head'])
print('\n第3部分')
print(cfg['owner'])
print('\n第4部分')
print(cfg['owner']['dob'],type(cfg['owner']['dob']))
print(cfg['owner']['dob2'],type(cfg['owner']['dob2']))
print(cfg['owner']['dob3'],type(cfg['owner']['dob3']))
print(cfg['owner']['dob4'],t
结果显示:
C:\ProgramData\Anaconda3\python.exe D:/my_python/实用例子/toml配置文件读取/demo-toml读取.py
{'mysql': {'host': 'localhost', 'user': 'root', 'port': 3306, 'database': 'an', 'password': 'jiang', 'parameters': {'pool_size': 5, 'charset': 'utf8'}, 'fields': {'pandas_cols': ['id', 'name', 'age', 'date']}}, 'head': {'title': 'TOML Example标题', 'subject': 'subject标题 Example', '汉字标题subject': '标题 Example'}, 'owner': {'name': 'Tom Preston-Werner演示', 'dob': datetime.datetime(1979, 5, 27, 7, 32, tzinfo=<toml.tz.TomlTz object at 0x00000000028F6A48>), 'dob2': datetime.datetime(2022, 12, 3, 9, 32, 1), 'dob3': datetime.datetime(2022, 12, 3, 9, 32, 1), 'dob4': datetime.date(2022, 12, 3)}, 'database': {'enabled': True, 'ports': [8000, 8001, 8002], 'data': [['delta', 'phi'], [3.14, 0.618]], 'temp_targets': {'cpu': 79.5, 'case': 72.0}}, 'servers': {'alias': 'sample1', 'alpha': {'ip': '10.0.0.1', 'role': 'frontend'}, 'beta': {'ip': '10.0.0.2', 'role': 'backend'}}}
第2部分
{'title': 'TOML Example标题', 'subject': 'subject标题 Example', '汉字标题subject': '标题 Example'}
第3部分
{'name': 'Tom Preston-Werner演示', 'dob': datetime.datetime(1979, 5, 27, 7, 32, tzinfo=<toml.tz.TomlTz object at 0x00000000028F6A48>), 'dob2': datetime.datetime(2022, 12, 3, 9, 32, 1), 'dob3': datetime.datetime(2022, 12, 3, 9, 32, 1), 'dob4': datetime.date(2022, 12, 3)}
第4部分
1979-05-27 07:32:00-08:00 <class 'datetime.datetime'>
2022-12-03 09:32:01 <class 'datetime.datetime'>
2022-12-03 09:32:01 <class 'datetime.datetime'>
2022-12-03 <class 'datetime.date'>
Process finished with exit code 0