常用模块(四)

八、configparser 模块

官方介绍:A configuration file consists of sections, lead by a "[section]" header,and followed by "name: value" entries,

with continuations and such in the style of RFC 822.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

ConfigParse 模块在 python3 中修改为 configparse ,此模块常用于生成和修改常见配置文档

 

Eg.编辑文档的配置文件

常见的文档格式

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

 

根据文档的格式要求来生成文件

import configparser

config = configparser.ConfigParser()
# 进行文件配置的第一种方式
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {'User' : 'hg'}

# 进行文件配置的第二种方式
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # 在字典中分别添加键值对
topsecret['ForwardX11'] = 'no'  

config['DEFAULT']['ForwardX11'] = 'yes'  # 为第一个字典添加键值对
with open('example.ini', 'w') as configfile:
    config.write(configfile)

 

configparse 模块的相关操作

工作方式:先把配置文件读取出来,放入一个对象中再进行相应的操作

import configparser

# 把配置文件放入一个对象中,进行读取操作
config = configparser.ConfigParser()
config.read('example.ini')
# 浏览配置文件中的内容
print(config.sections())
>>> ['bitbucket.org', 'topsecret.server.com']
print(config.defaults()) # defaults 为特殊的单元,需要单独进行操作
>>> OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'yes')])

# 对配置文件进行取值
print(config['bitbucket.org']['User'])
for key in config['bitbucket.org']: print(key) # default为特殊的单元,无论对谁进行打印它都会跟着
>>> hg
    user
    compressionlevel
    serveraliveinterval
    compression
    forwardx11

# 删除数据的两种方法
config.remove_section('topsecret.server.com')
config.remove_option('bitbucket.org','user')

config.set('bitbucket.org','user','Mike')
print(config.has_section('topsecret.server.com'))
>>> False

# 修改数据
config.write(open('example.ini', "w"))  # 文件一旦写入后不能修改,此操作为重新创建一个名字相同文件,并进行相应的增加、删除、修改操作

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄