python ConfigParser

本文介绍ConfigParser模块的使用方法,包括初始化、读取配置文件、获取section和options、按类型读取配置项等。同时提供了修改配置项、添加section及选项、删除section或选项的示例。
一、ConfigParser简介

ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

1: [db]

2: db_host = 127.0.0.1

3: db_port = 22

4: db_user = root

5: db_pass = rootroot

6: 

7: [concurrent]

8: thread = 10

9: processor = 20

中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。

 

二、ConfigParser 初始工作

使用ConfigParser 首选需要初始化实例,并读取配置文件:

1: cf = ConfigParser.ConfigParser()

2: cf.read("配置文件名")

 

三、ConfigParser 常用方法

1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:

1: s = cf.sections()

2: print 'section:', s

将输出(以下将均以简介中配置文件为例):

1: section: ['db', 'concurrent']

2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:

1: o = cf.options("db")

2: print 'options:', o

将输出:

1: options: ['db_host', 'db_port', 'db_user', 'db_pass']

3. 获取指定section 的配置信息

1: v = cf.items("db")

2: print 'db:', v

将输出:

1: db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]

4. 按照类型读取指定section 的option 信息

同样的还有getfloat、getboolean。

1: #可以按照类型读取出来

2: db_host = cf.get("db""db_host")

3: db_port = cf.getint("db""db_port")

4: db_user = cf.get("db""db_user")

5: db_pass = cf.get("db""db_pass")

6: 

7: # 返回的是整型的

8: threads = cf.getint("concurrent""thread")

9: processors = cf.getint("concurrent""processor")

10: 

11: print "db_host:", db_host

12: print "db_port:", db_port

13: print "db_user:", db_user

14: print "db_pass:", db_pass

15: print "thread:", threads

16: print "processor:", processors

将输出:

1: db_host: 127.0.0.1

2: db_port: 22

3: db_user: root

4: db_pass: rootroot

5: thread: 10

6: processor: 20

5. 设置某个option 的值。(记得最后要写回)

1: cf.set("db""db_pass""zhaowei")

2: cf.write(open("test.conf""w"))

6.添加一个section。(同样要写回)

1: cf.add_section('liuqing')

2: cf.set('liuqing', 'int', '15')

3: cf.set('liuqing', 'bool', 'true')

4: cf.set('liuqing', 'float', '3.1415')

5: cf.set('liuqing', 'baz', 'fun')

6: cf.set('liuqing', 'bar', 'Python')

7: cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!')

8: cf.write(open("test.conf""w"))

7. 移除section 或者option 。(只要进行了修改就要写回的哦)

1: cf.remove_option('liuqing','int')

2: cf.remove_section('liuqing')

3: cf.write(open("test.conf""w"))
### Python `configparser` 模块的使用说明 #### 简介 `configparser` 是 Python 中用于处理配置文件的一个标准库模块。它允许开发者通过 INI 风格的配置文件来管理应用程序的设置[^4]。 #### 基本功能 该模块支持读取、写入以及修改配置文件的内容。以下是其主要功能: - **解析配置文件**:可以轻松加载 `.ini` 文件并从中提取键值对。 - **更新配置项**:能够动态更改配置文件中的值。 - **保存配置到文件**:可将内存中的配置数据重新写回到磁盘上的文件中。 #### 示例代码 以下是一个简单的例子展示如何创建、读取和修改配置: ```python import configparser # 创建 ConfigParser 对象 config = configparser.ConfigParser() # 添加一节 (section) 并设定一些选项 (options) config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # 将配置写入文件 with open('example.ini', 'w') as configfile: config.read_dict(config._sections) # 可选操作,仅当需要从字典初始化时使用 config.write(configfile) # 读取已有的配置文件 config.read('example.ini') # 访问特定 section 的 option 值 print(config['bitbucket.org']['User']) # 输出: hg # 修改现有 value 或者添加新 key-value pair config.set('topsecret.server.com', 'PasswordAuthentication', 'no') ``` 以上脚本展示了怎样定义默认参数、增加新的 sections 和 options、把整个结构存回硬盘以及查询指定条目的具体方法[^5]。 #### 日志记录集成 如果希望结合日志系统一起工作,则可以通过如下方式实现更复杂的场景应用: ```python import logging.config cfg_file_path = '/path/to/logging.conf' logging.config.fileConfig(cfg_file_path) logger = logging.getLogger(__name__) if __name__ == "__main__": logger.debug("This is a debug message.") ``` 这里假设存在名为 `logging.conf` 的外部配置文档,其中包含了关于不同 handler 类型及其属性的信息。这样做的好处在于分离业务逻辑与基础设施级别的细节描述[^6]。 #### 注意事项 尽管 `configparser` 提供了许多便利之处,但在实际开发过程中仍需注意几点最佳实践建议: - 总是以 UTF-8 编码存储您的配置文件以确保兼容性和一致性; - 谨慎对待敏感信息比如密码之类的字段最好加密后再放入配置当中; - 定期备份重要配置以防意外丢失;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值