
前文已经讲过 configparser读写ini配置文件的基本操作
Python配置文件解析configparser
进一步使用这个 configparser模块的其他特性
configparser可以从ini文件读取配置,也可以从dic中解析配置
也可以从字符串中解析配置如下
sample_config = """
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb
# we don't need ACID today
skip-innodb
"""
config = configparser.ConfigParser(allow_no_value=True)
config.read_string(sample_config)
print(config["mysqld"]["user"])

如何在ini中动态取配置
[DEFAULT]
hash = #
[bitbucket.org]
shebang = ${hash}!/usr/bin/env python
shebang_2 = %(hash)s!/usr/bin/env python
hash = # 这个配置项中的值是一个 # ,但是其他的配置项的的值需要用到 这个
shebang = ${hash}!/usr/bin/env python
shebang_2 = %(hash)s!/usr/bin/env python
使用了两种办法
- ${hash}! 取不到这个hash的值
- %(hash) 可以正常输出
${hash}!/usr/bin/env python
#!/usr/bin/env python

这种使用%在ini文件中动态取其他配置项的值是不同的配置中有依赖关系,列如定义一个dir目录项,而文件路径需要用到这个dir组成一个完整的文件路径,这种配置之间的依赖关系比较常见。
例如下面的配置之间是有依赖关系的 home_dir依赖于 users_dir和name
[info]
users_dir= C:Users
name= Jano
home_dir= %(users_dir)s\%(name)s
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...


