资讯专栏INFORMATION COLUMN

python模块之configparser

荆兆峰 / 1839人阅读

摘要:由于这种需求非常普遍,配置解析器提供了一系列更简便的方法来处理整数浮点数及布尔值。注意点方法对大小写不敏感,能识别和为对应的布尔值后备值和字典一样,可以使用的方法提供后备值需要注意的是,默认值的优先级高于后备值。

快速开始
# 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类的实例可以对其进行读写操作。

创建配置文件:

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)

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

读取配置文件:

>>> 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())。用户也可以自行注册转换器或定制配置解析器已提供的转换器。

>>> 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()方法提供后备值:

>>> topsecret.get("CompressionLevel")
"9"
>>> topsecret.get("Cipher")
>>> topsecret.get("Cipher", "3des-cbc")
"3des-cbc

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

>>> topsecret.get("CompressionLevel", "3")
"9"

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

>>> 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名称区分大小写,键不区分大小写。

键、值的头部和尾部空格自动移除。

值可以省略,在这种情况下分隔符也可以不要。

值可以跨多行,只要其他行的值比第一行的值缩进更深。

空行可以被忽略或视作多行值的一部分(取决于解析器模式)。

可以包含注解,独占一行显示,默认以字符#;为前缀。应该避免注解与键或值处在同一行,因为这将导致把注解视为值的一部分。

[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中的值。其他默认值可以在初始化时提供。

[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的值)

[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:

"a" in parser["section"]
"A" in parser["section"]

所有section都包含DEFAULTSECT的值,也就是说,对section的.clear()操作可能并没有真正的清空,这是因为无法从该section删除默认值。在除DEFAULTSECT以外的section上删除默认值(前提是没有对默认值重写)将抛出KeyError异常

>>> 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

>>> 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中的格式化字符串是否插值表示

>>> list(config.items())
[("DEFAULT", ), ("bitbucket.org", ), ("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异常,而不会直接忽略

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="")
从字符串中解析配置数据

read_dict(dictionary, source="")
从提供类似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属性(接收一个字符串参数并返回一个新的字符串的函数)改变默认行为。

cfgparser = ConfigParser()
cfgparser.optionxform = str

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

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

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

RawConfigParser对象

省略

异常

省略

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42610.html

相关文章

  • Python解析配置模块ConfigParser详解

    摘要:解析配置模块之详解基本的读取配置文件直接读取文件内容得到所有的,并以列表的形式返回得到该的所有得到该的所有键值对得到中的值,返回为类型得到中的值,返回为类型,还有相应的和函数。是最基础的文件读取类,支持对变量的解析。 Python 解析配置模块之ConfigParser详解 1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有...

    weknow619 评论0 收藏0
  • python--模块2

    摘要:可能没有用户输出的消息创建一个,用于写入日志文件再创建一个,用于输出到控制台对象可以添加多个和对象序列化模块什么叫序列化将原本的字典列表等内容转换成一个字符串的过程就叫做序列化。 hashlib模块 1.Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(...

    13651657101 评论0 收藏0
  • 【自动化测试】Python 读取 .ini 格式文件

    摘要:大家应该接触过格式的配置文件。特别是后续做自动化的测试,需要拎出一部分配置信息,进行管理。二读取文件自带有读取配置文件的模块,配置文件不区分大小写。读取文件内容得到所有的,并以列表的形式返回。 大家应该接触过.ini格式的配置文件。配置文件就是把一些配置相关信息提取出去来进行单独管理,如果以后有变动只需改配置文件,无需修改代码。特别是后续做自动化的测试,需要拎出一部分配置信息,进行管...

    Eric 评论0 收藏0
  • PyCharm的安装、设置及使用

    摘要:的简介随着近年来的火爆程度逐年攀升越来越多的开发者开始因其丰富的库支持简洁高效的语法以及强大的运算速度而对其纷纷侧目也正因此及基于它而生的各类框架如等普遍应用于当下各类场景下作为时代的弄潮儿大有独领风骚之势也正是因此毫无疑问是当前最好的编程 PyCharm的简介 随着近年来Python的火爆程度逐年攀升,越来越多的开发者开始因其丰富的库支持,简洁高效的语法以及强大的运算速度而对其纷纷侧...

    jzzlee 评论0 收藏0
  • Python Tips

    摘要:的三种数据类型字典列表元组,分别用花括号中括号小括号表示。约等于上句,可能是因为自定义变量名与内部函数或变量同名了。下,默认路径一般为。的日志模块中计时器定时器计划任务,。对象的问题怎样忽略警告不打印烦人的警告打印到终端同时记录到文件。 Python Enhancement Proposal。(PEP,Python增强建议书) Python之禅(import this) Pytho...

    Reducto 评论0 收藏0

发表评论

0条评论

荆兆峰

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<