ZetCode

Python ConfigParser

最后修改于 2024 年 1 月 29 日

Python ConfigParser 教程展示了如何使用 ConfigParser 在 Python 中处理配置文件。

Python ConfigParser

ConfigParser 是一个 Python 类,它实现了一个基础的 Python 程序配置文件语言。它提供了与 Microsoft Windows INI 文件类似的结构。ConfigParser 允许编写易于最终用户自定义的 Python 程序。

配置文件由节(sections)后跟选项的键/值对组成。节的名称由 [] 字符分隔。键值对则用 := 分隔。注释以 #; 开始。

Python ConfigParser 读取文件

在第一个示例中,我们从文件中读取配置数据。

db.ini
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb

[postgresql]
host = localhost
user = user8
passwd = mypwd$7
db = testdb

我们有两个配置数据节。

reading_from_file.py
#!/usr/bin/python

import configparser

config = configparser.ConfigParser()
config.read('db.ini')

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print('MySQL configuration:')

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

print('PostgreSQL configuration:')

print(f'Host: {host2}')
print(f'User: {user2}')
print(f'Password: {passwd2}')
print(f'Database: {db2}')

该示例读取 MySQL 和 PostgreSQL 的配置数据。

config = configparser.ConfigParser()
config.read('db.ini')

我们初始化 ConfigParser 并使用 read 方法读取文件。

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

我们访问 mysql 节中的选项。

host2 = config['postgresql']['host']
user2 = config['postgresql']['user']
passwd2 = config['postgresql']['passwd']
db2 = config['postgresql']['db']

我们访问 postgresql 节中的选项。

$ python reading_from_file.py
MySQL configuration:
Host: localhost
User: user7
Password: s$cret
Database: ydb
PostgreSQL configuration:
Host: localhost
User: user8
Password: mypwd$7
Database: testdb

Python ConfigParser 节

配置数据被组织到节中。sections 方法读取所有节,而 has_section 方法检查是否存在指定的节。

sections.py
#!/usr/bin/python

import configparser

config = configparser.ConfigParser()
config.read('db.ini')

sections = config.sections()
print(f'Sections: {sections}')

sections.append('sqlite')

for section in sections:

    if config.has_section(section):
      print(f'Config file has section {section}')
    else:
      print(f'Config file does not have section {section}')

该示例处理节。

$ python sections.py
Sections: ['mysql', 'postgresql']
Config file has section mysql
Config file has section postgresql
Config file does not have section sqlite

Python ConfigParser 从字符串读取

从 Python 3.2 开始,我们可以使用 read_string 方法从字符串读取配置数据。

read_from_string.py
#!/usr/bin/python

import configparser

cfg_data = '''
[mysql]
host = localhost
user = user7
passwd = s$cret
db = ydb
'''

config = configparser.ConfigParser()
config.read_string(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

该示例从字符串读取配置。

Python ConfigParser 从字典读取

从 Python 3.2 开始,我们可以使用 read_dict 方法从字典读取配置数据。

read_from_dict.py
#!/usr/bin/python

import configparser

cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
              'passwd': 's$cret', 'db': 'ydb'}
}

config = configparser.ConfigParser()
config.read_dict(cfg_data)

host = config['mysql']['host']
user = config['mysql']['user']
passwd = config['mysql']['passwd']
db = config['mysql']['db']

print(f'Host: {host}')
print(f'User: {user}')
print(f'Password: {passwd}')
print(f'Database: {db}')

该示例从 Python 字典读取配置。

cfg_data = {
    'mysql': {'host': 'localhost', 'user': 'user7',
                'passwd': 's$cret', 'db': 'ydb'}
}

键是节的名称,值是包含节中存在的键值对的字典。

Python ConfigParser 写入

write 方法用于写入配置数据。

writing.py
#!/usr/bin/python

import configparser

config = configparser.ConfigParser()

config.add_section('mysql')

config['mysql']['host'] = 'localhost'
config['mysql']['user'] = 'user7'
config['mysql']['passwd'] = 's$cret'
config['mysql']['db'] = 'ydb'

with open('db3.ini', 'w') as configfile:
    config.write(configfile)

该示例将配置数据写入 db3.ini 文件。

config.add_section('mysql')

首先,我们使用 add_section 添加一个节。

config['mysql']['host'] = 'localhost'
config['mysql']['user'] = 'user7'
config['mysql']['passwd'] = 's$cret'
config['mysql']['db'] = 'ydb'

然后我们设置选项。

with open('db3.ini', 'w') as configfile:
    config.write(configfile)

最后,我们使用 write 方法写入数据。

Python ConfigParser 插值

ConfigParser 允许在配置文件中使用插值。它使用 % 语法。

cfg.ini
[info]
users_dir= C:\Users
name= Jano
home_dir= %(users_dir)s\%(name)s

我们使用插值构建 home_dir。请注意,'s' 字符是语法的一部分。

interpolation.py
#!/usr/bin/python

import configparser

config = configparser.ConfigParser()
config.read('cfg.ini')

users_dir = config['info']['users_dir']
name = config['info']['name']
home_dir = config['info']['home_dir']

print(f'Users directory: {users_dir}')
print(f'Name: {name}')
print(f'Home directory: {home_dir}')

该示例读取值并打印它们。

$ python interpolation.py
Users directory: C:\Users
Name: Jano
Home directory: C:\Users\Jano

来源

Python ConfigParser 文档

在本文中,我们使用了 ConfigParser 来处理 Python 中的配置数据。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程