这些可以动态改变的值,可以放在一个单独的配置文件中,这样程序代码不需要变化,只需要调整配置文件中的值即可。
ConfigParser是一个 Python 类,为 Python 程序实现基本的配置语言。 它提供类似于 Microsoft Windows INI 文件的结构
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes
import configparserconfig = configparser.ConfigParser()config.read('my.ini')DEFAULT = config['DEFAULT'] print(DEFAULT, )a = DEFAULT['ServerAliveInterval']print(a)
其实你可以理解为这样的结构 config['DEFAULT']的值是一个字典,代码下面的配置信息
config['DEFAULT'] = {'ServerAliveInterval': '45',... 'Compression': 'yes',... 'CompressionLevel': '9'}
卷面我们知道用中括号饭团的一行为一个段[DEFAULT],如何获取所有的这样的段
sections = config.sections()
import configparserconfig = configparser.ConfigParser()config.read('my.ini') sections = config.sections()print(f'Sections: {sections}')
Sections: ['bitbucket.org', 'topsecret.server.com']
[DEFAULT-1]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no
Sections: ['DEFAULT-1', 'bitbucket.org', 'topsecret.server.com']
从上面的结构我们可以发现其实这个ini文件和字典结构很类似
可以使用read_dict来从字典中解析配置
cfg_data = { 'DEFAULT': { 'ServerAliveInterval': '45', 'Compression' : 'yes', 'CompressionLevel' : '9', 'ForwardX11' : 'yes' }, 'bitbucket.org': {'User': 'hg'} , 'topsecret.server.com': { 'Port' : '50022', 'ForwardX11' : 'no', },}config = configparser.ConfigParser()config.read_dict(cfg_data)print(config)sections = config.sections()print(f'Sections: {sections}')
config.read_dict(cfg_data)
config = configparser.ConfigParser()config.add_section('NEW-CONFIG')config['NEW-CONFIG']['host'] = 'localhost'config['NEW-CONFIG']['user'] = 'user7'config['NEW-CONFIG']['passwd'] = 's$cret'config['NEW-CONFIG']['db'] = 'ydb'with open('my.ini', 'a') as configfile: config.write(configfile)
可以看到新增加了一个段和配置项[NEW-CONFIG],注意里面的换行问题
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no[NEW-CONFIG]host = localhostuser = user7passwd = s$cretdb = ydb
下面的配置文件,目录,文件名 最后一个是完整的文件路径 是人家两个配置计算出来的
%(users_dir)s\%(name)s表示使用 users_dir和 name这两个配置的值拼接起来的
请注意,“ s”字符是语法的一部分。
my.ini配置文件内容
[info]users_dir= C:\Usersname= Janohome_dir= %(users_dir)s\%(name)s
home_dir = config['info']['home_dir']print(home_dir)
Sections: ['bitbucket.org', 'topsecret.server.com', 'NEW-CONFIG', 'info']C:\Users\Jano
联系客服