优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python配置文件解析configparser

nanyue 2024-12-10 18:58:36 技术文章 7 ℃

写一个程序的时候有些内容需要动态调整

这些可以动态改变的值,可以放在一个单独的配置文件中,这样程序代码不需要变化,只需要调整配置文件中的值即可。

Python ConfigParser

ConfigParser是一个 Python 类,为 Python 程序实现基本的配置语言。 它提供类似于 Microsoft Windows INI 文件的结构

  • 配置文件由各部分组成,后跟选项的键/值对。
  • 段名用[]字符分隔。 这些对用:=隔开。 注释以#;开头。


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

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
  • [DEFAULT]表示一段配置
  • ServerAliveInterval = 45表示一个key-value的配置
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  • 如何取到 ServerAliveInterval对应的值45?

import configparser
config = 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 configparser
config = configparser.ConfigParser()
config.read('my.ini')
 
sections = config.sections()
print(f'Sections: {sections}')
Sections: ['bitbucket.org', 'topsecret.server.com']
  • 输出中少了一个DEFAULT段,实际上这个是默认的段。

把这个段的修改修为 DEFAULT-1 就可以获取所有的段名了

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

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
Sections: ['DEFAULT-1', 'bitbucket.org', 'topsecret.server.com']

使用字典代码ini文件

从上面的结构我们可以发现其实这个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)  

通过程序添加新的配置项

  • add_section添加一个段
  • 然后加入配置项
  • 最后写入文件

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 = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

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

[NEW-CONFIG]
host = localhost
user = user7
passwd = s$cret
db = ydb

ini文件中的一些技巧

下面的配置文件,目录,文件名 最后一个是完整的文件路径 是人家两个配置计算出来的

%(users_dir)s\%(name)s表示使用 users_dir和 name这两个配置的值拼接起来的

请注意,“ s”字符是语法的一部分。


my.ini配置文件内容


[info]
users_dir= C:\Users
name= Jano
home_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
最近发表
标签列表