前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python模块之configparser

python模块之configparser

作者头像
枇杷李子橙橘柚
发布2022-06-15 08:05:51
8690
发布2022-06-15 08:05:51
举报
文章被收录于专栏:没有擅长的YcY没有擅长的YcY

快速开始

代码语言:javascript
复制
# demo.ini

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

[bitbucket.org]
User = hg

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

上面的demo.ini是一个非常基础的配置文件,它由多个部分(section)组成,每部分包含了带值的选项。ConfigParse类的实例可以对其进行读写操作。

创建配置文件:

代码语言:javascript
复制
import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {"ServerAliveInterval": "45",
                     "Compression": "yes",
                     "CompressionLevel": "9",
                     "ForwardX11": "yes"}

config["bitbucket.org"] = {}
config["bitbucket.org"]["User"] = "hg"

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret["Port"] = "50022"
topsecret["ForwardX11"] = "no"

with open("demo.ini", "w") as configfile:
    config.write(configfile)

对配置解析器的处理与字典类似。

读取配置文件:

代码语言:javascript
复制
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read("demo.ini")
["demo.ini"]
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> "bitbucket.org" in config
True
>>> "bitbong.com" in config
False
>>> config["bitbucket.org"]["User"]
"hg"
>>> config['DEFAULT']['Compression']
"yes"
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
"no"
>>> for key in config["bitbucket.org"]:
...     print(key)
user
serveraliveinterval
compression
compressionlevel
forwardx11
>>> config["bitbucket.org"]["ForwardX11"]
"yes"

注意点:[DEFAULT]为其他所有section提供默认值,section中的所有键大小写不敏感并以小写字母存储

支持的数据类型

配置解析器总是存储配置的值为字符串类型,因此用户需要按需转换为期望的数据类型。由于这种需求非常普遍,配置解析器提供了一系列更简便的方法来处理整数(getint())、浮点数(getfloat())及布尔值(getboolean())。用户也可以自行注册转换器或定制配置解析器已提供的转换器。

代码语言:javascript
复制
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True

注意点:getboolean()方法对大小写不敏感,能识别'yes'/'no', 'on'/'off', 'true'/'false'和'1'/'0'为对应的布尔值

后备值(Fallback Values)

和字典一样,可以使用section的get()方法提供后备值:

代码语言:javascript
复制
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc

需要注意的是,默认值的优先级高于后备值。比如要想在'topsecret.server.com'中获取'CompressionLevel'的值,即使指定了后备值,仍然得到的是'DEFAULT'中的值:

代码语言:javascript
复制
>>> topsecret.get('CompressionLevel', '3')
'9'

此外,除了section的get()方法,还提供了解析器级别的get()方法,支持向后兼容,后备值通过fallback关键字指定:

代码语言:javascript
复制
>>> config.get("bitbucket.org", "monster", fallback="No such things as monsters")
"No such things as monsters"

fallback关键字同样支持在getint(), getfloat()getboolean()中使用

支持的INI文件结构

  • 配置文件由section组成,每个section以[section_name]的形式打头,后跟以特定字符(默认是=:)分隔的键值对。
  • 默认情况下section名称区分大小写,键不区分大小写。
  • 键、值的头部和尾部空格自动移除。
  • 值可以省略,在这种情况下分隔符也可以不要。
  • 值可以跨多行,只要其他行的值比第一行的值缩进更深。
  • 空行可以被忽略或视作多行值的一部分(取决于解析器模式)。
  • 可以包含注解,独占一行显示,默认以字符#;为前缀。应该避免注解与键或值处在同一行,因为这将导致把注解视为值的一部分。
代码语言:javascript
复制
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?

插值

ConfigParser支持插值,调用get()方法返回值之前将对值进行预处理

class configparser.BasicInterpolation

默认使用的Interpolation类。允许值包含格式化字符串,该字符串引用同一section中的值或DEFAULTSECTsection中的值。其他默认值可以在初始化时提供。

代码语言:javascript
复制
[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

在上面的例子中,interpolation设置为BasicInterpolation()的ConfigParser将解析%(home_dir)shome_dir的值,%(my_dir)s将解析为/Users/lumberjack。引用链中使用的键不需要在配置文件中以任何特定的顺序指定。

如果interpolation设置为None,将直接返回%(home_dir)s/lumberjack作为my_dir的值。

class configparser.ExtendedInterpolation

扩展的Interpolation类,实现了更高级的语法。它使用${section:option}表示来自外部section的值,如果省去了section:,默认指当前section(以及可能的DEFAULTSECTsection的值)

代码语言:javascript
复制
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}

映射协议访问

映射协议访问是允许像操作字典一样使用自定义对象的功能的通用名称。在configparser中,映射接口通过parser["section"]["option"]的形式实现。

parser["section"]返回解析器中section的值的代理,值从原始解析器中获取但并非通过复制的方式。在section代理上改变值的操作,实际上是对原始解析器的改变。

configparser对象虽然表现的尽可能接近字典,但仍有一些区别需要注意:

  • 默认情况下,section中的所有key能够以大小写不敏感的方式访问。例如for option in parser["section"]语句生成的option名称总是被optionxform函数转换为小写。拥有"a"选项的section通过以下两种方式访问都将返回True:
代码语言:javascript
复制
"a" in parser["section"]
"A" in parser["section"]
  • 所有section都包含DEFAULTSECT的值,也就是说,对section的.clear()操作可能并没有真正的清空,这是因为无法从该section删除默认值。在除DEFAULTSECT以外的section上删除默认值(前提是没有对默认值重写)将抛出KeyError异常
代码语言:javascript
复制
>>> del topsecret["forwardx11"]
>>> topsecret["forwardx11"]
'yes'
>>> del topsecret["serveraliveinterval"]
Traceback (most recent call last):
  ...
    raise KeyError(key)
KeyError: 'serveraliveinterval'
  • DEFAULTSECT不能从解析器移除
    • 删除它将抛出ValueError异常
    • parser.clear()操作对它没有任何影响
    • parser.popitem()不会返回DEFAULTSECT
代码语言:javascript
复制
>>> del config["DEFAULT"]
Traceback (most recent call last):
  ...
    raise ValueError("Cannot remove the default section.")
ValueError: Cannot remove the default section.
>>> config.clear()
>>> config["DEFAULT"]["serveraliveinterval"]
'45'
  • parser.get(section, option, **kwargs) - 第二个参数并非字典的get()方法表示的后备值,但section级别的get()方法与映射协议却是兼容的
  • parser.items(raw=False, vars=None)兼容映射协议(返回包含DEFAULTSECT的(section_name, section_proxy)对的列表)。另有指定section的调用方式:parser.items(section, raw=False, vars=None).后者返回指定section的(option, value)对的列表,raw参数指定value中的格式化字符串是否插值表示
代码语言:javascript
复制
>>> list(config.items())
[('DEFAULT', <Section: DEFAULT>), ('bitbucket.org', <Section: bitbucket.org>), ('topsecret.server.com', <Section: topsecret.server.com>)]
>>> list(config.items("bitbucket.org"))
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

自定义解析器行为

省略

旧版API示例

省略

ConfigParser对象

class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})

defaults() 返回包含实例范围默认值的字典

sections() 返回可用section的名称列表(不包含默认section的名称)

add_section(section) 添加section。如果该section已经存在,抛出DuplicateSectionError异常;如果传入的是默认section的名称,抛出ValueError异常;如果传入的参数不是字符串类型,抛出TypeError异常

has_section(section) 判断section是否存在。默认section总是返回False

options(section) 返回指定section的可用选项列表(包含DEFAULTSECT中的选项)。指定默认section将抛出NoSectionError异常

has_option(section, option) 如果section存在且包含指定的option,返回True,否则返回False。如果传递的section为None"",视为默认section

read(filenames, encoding=None) 读取并解析可迭代的文件名,返回成功解析的文件名列表

如果filenames是一个字符串,或字节对象又或者是类路径对象,视其为单个文件。如果filenames中的某个文件不能打开,该文件将被忽略

如果filenames中所有文件都不存在,ConfigParser实例将包含空数据集。如果某个应用需要导入初始化值,应该在调用read()导入可选配置文件前调用read_file()读取相应的初始化配置文件,因为read_file()读取不能打开的文件时会抛出FileNotFoundError异常,而不会直接忽略

代码语言:javascript
复制
import configparser, os

config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
            encoding='cp1250')

read_file(f, source=None) 从可迭代生成Unicode字符串的f(例如以文本模式打开的文件对象)读取及解析配置数据

read_string(string, source='<string>') 从字符串中解析配置数据

read_dict(dictionary, source='<dict>') 从提供类似dict的items()方法的对象加载配置。key是section名称,value是包含选项和值的字典。如果使用的字典类型支持保留顺序,section及其选项将按序添加,所有值自动转换为字符串

get(section, option, * , raw=False, vars=None[, fallback]) 获取指定section的选项的值。vars参数作为字典对象传递。option按照vars,section,DEFAULTSECT的顺序进行查找,如果不存在且提供了fallback参数,返回fallback的值,fallback可以是None

raw参数指定value中的格式化字符串是否插值表示,与option的查找顺序相同

getint(section, option, * , raw=False, vars=None[, fallback]) 转换option的值为int类型

getfloat(section, option, * , raw=False, vars=None[, fallback]) 转换option的值为float类型

getboolean(section, option, * , raw=False, vars=None[, fallback]) 转换option的值为bool类型

items(raw=False, vars=None) items(section, raw=False, vars=None) 前者返回包含DEFAULTSECT的(section_name, section_proxy)对的列表。后者返回指定section的(option, value)对的列表

set(section, option, value) 如果section存在,设置option的值为value,否则抛出NoSectionError异常。option和value必须是字符串类型,否则抛出TypeError异常

write(fileobject, space_around_delimiters=True) 将ConfigParser对象写入以文件模式打开的文件。

remove_option(section, option) 从section中移除指定的选项。如果section不存在,抛出NoSectionError异常。如果option存在返回True,否则返回False

remove_section(section) 移除指定section。如果section存在返回True,否则返回False(对默认section的操作总是返回False)

optionxform(option) 对option的处理函数,默认返回option的小写形式。可以通过继承重写或设置ConfigParser实例的optionxform属性(接收一个字符串参数并返回一个新的字符串的函数)改变默认行为。

代码语言:javascript
复制
cfgparser = ConfigParser()
cfgparser.optionxform = str

读取配置文件时,option两边的空格在调用此函数前先被移除

readfp(fp, filename=None) 已弃用,使用 read_file()替代

configparser.MAX_INTERPOLATION_DEPTH 当raw参数为false时,get()方法递归插值的最大深度。仅在使用默认的BasicInterpolation时才有意义

RawConfigParser对象

省略

异常

省略

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 快速开始
  • 支持的数据类型
  • 后备值(Fallback Values)
  • 支持的INI文件结构
  • 插值
    • class configparser.BasicInterpolation
      • class configparser.ExtendedInterpolation
      • 映射协议访问
      • 自定义解析器行为
      • 旧版API示例
      • ConfigParser对象
      • RawConfigParser对象
      • 异常
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档