Python ConfigParser 教程

Python ConfigParser 教程介绍了如何使用 ConfigParser 在 Python 中使用配置文件。

Python ConfigParser

ConfigParser是一个 Python 类,为 Python 程序实现基本的配置语言。 它提供类似于 Microsoft Windows INI 文件的结构。 ConfigParser允许编写可由最终用户轻松定制的 Python 程序。

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

Python ConfigParser读取文件

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

db.ini

[mysql]
host = localhost
user = user7
passwd = scret
db = ydb

[postgresql]
host = localhost
user = user8
passwd = mypwd7
db = testdb

我们有两部分配置数据。

reading_from_file.py

#!/usr/bin/env python3

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/env python3

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/env python3

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/env python3

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/env python3

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/env python3

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

在本教程中,我们使用ConfigParser处理 Python 中的配置数据。

您可能也会对以下相关教程感兴趣: Python 教程Python 哈希教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程