Python ConfigParser模块

Python ConfigParser模块

Python内置的ConfigParser库是基础模块的一部分。该库提供了一个控制台解析器,用于简化由名称-键值对组成的文件配置。

该库支持全球通用的约定是“INI”语法,最常用于Microsoft平台。该库最初是为了帮助处理不同语言结构,其中每个段中的项目看起来像RFC 822头部。

该实现允许使用任一语法来确定命名值。这种不明显的失误和“INI”设计缺乏明确的定义,使得该模块的维护非常繁琐,因此在几乎每个Python版本中都对其进行了更改,模块的行为方式也变得非常枯燥。

重要观点

  • 默认值的持续行为一直都是计划的。
  • 该模块旨在支持一组程序,这些程序可以直接使用某些数据,或者形成其他值的部分(例如,包括运行程序的计算机的主机名的路径名)。
  • 当时有一个需要区分不同目的的“默认”值的强烈原因,就像MartinManey在下面提到的。 (目前对我来说还不清楚,因为ConfigParser提供的API是附加的。)
  • 最近实现中对现有“默认值”的使用魔法段名称是我认为令人遗憾的事情;默认字典应该与各个区域的字典不同。
  • 如果有任何额外的名称空格(“默认类型”)被考虑到,我希望它们不会成为由愚蠢的失误引起的部分名称排列的一部分。
  • 通过write()方法将默认值合并进去是令人遗憾的;这些默认值是为应用程序提供已处理的值的一种方式,如果特定的设置没有对其进行覆盖,将使用这些值。
  • 从Python的标准库中,configparser模块定义了Windows操作系统Microsoft使用的读取和写入配置文件的功能。
  • 这些文件通常具有.INI扩展名。
  • INI文件由[section]标题驱动的段组成。在方括号之间,我们可以放置部分的名称。
  • 段后面是由=或:字符分隔的键/值条目。它可以包含以#或;符号为前缀的注释。

以下是一个INI文件示例:

[Settings]
# Setting log detailed for extra debugging information
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Setting the location of the log file MV_FTP 
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown
[FTP]
# Setting the server active FTP
RunFTP=1
# defining the control port FTP
FTPPort=21
# Setting the locations of the data directory FTP
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# Setting the Name of admin
UserName=admin
# Setting the protected Password
Password=admin

ConfigParser类属于configparser模块。它必须管理解析的内容数据库并解析所有配置文档。

通过以下代码创建ConfigParser类的任意对象-

Parser_name = configparser.ConfigParser()

以下是与ConfigParser类的对象一起使用的方法:

write() 方法 以 .ini 格式了解配置的状态。
read_dict() 方法 从字典中读取配置。关键概念对于片段名称很重要,而值是具有应该存在于片段中的键和值的单词引用。
read_string() 方法 从任意字符串读取配置。
remove_option() 方法 从部分中删除任意选项。
has_option() 方法 返回部分中是否存在任意选项。
has_section() 方法 返回部分是否存在。
read() 方法 读取和解析任意配置文档。
items() 方法 对于部分中的每个选项,返回一个元组(值,名称)。
getboolean() 方法 类似于 get() 方法,但将值转换为布尔值。返回 True 或 False 值。
options() 方法 返回部分名称的配置选项列表。
read_file() 方法 读取和解析一个配置文档,作为文档对象。
getint() 方法 类似于 get(),但将值转换为整数。
get() 方法 返回指定选项的字符串值。
getfloat() 方法 类似于 get(),但将值转换为浮点数。
sections() 方法 返回部分名称的所有配置部分。
remove_section() 方法 删除部分的任何文档部分及其所有选项。
set() 方法 设置任意选项。

以下脚本解析并读取 ‘sampleconfigfile.ini’ 文件

import configparser_name
parser_name = configparser_name.ConfigParser_name()
parser_name.read('sampleconfig.ini')
for sect in parser_name.section():
   print('Sections:', sect_)
   for k1,v1 in parser_name.items(sect_):
      print(' {} = {}'.format(k1,v1))
   print()

输出:

Sections: Settings
detailedlog = 1
runstatus = 1
statusport = 6099
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin

为了构建一个配置文件,使用write()方法。下面的代码配置了 parser_name 的对象,并执行写操作到一个名为 ‘testing.ini’ 的文件对象

import configparser_name_name
parser_name_name = configparser_name_name.ConfigParser_name_name()
parser_name_name.add_section('Client')
parser_name_name.set('Client', 'Name', 'Asho Kulkarn')
parser_name_name.set('Client', 'email', 'asho@gmail.com')
parser_name_name.set('Client', 'password', 'secret')
fp=open('test.ini','w')
parser_name_name.write(fp)
fp.close()

支持的数据类型

在配置文件中,配置解析器(parser_names)不能假设值的数据类型,始终将其作为字符串保留在内部。这意味着如果我们需要其他数据类型,我们必须进行隐式转换:

> > > int(top_secrets['Port'])
50225
> > > float(top_secrets['CompressionLevels'])
8.0

由于这份工作非常普通,配置解析器为处理数字、浮点数和布尔值提供了一系列有用的getter技巧。最后一种技巧最有趣,因为将值传递给bool()是没有用的,因为bool(‘true’)仍然是false。这就是为什么配置解析器还提供了getboolean()方法。该方法是区分大小写的,并将布尔值识别为’no’/’yes’、’false’/’true’、’off’/’on’和’0’/’1’。

例如:

> > >
> > > top_secret.getboolean('ForwardX11')
False
> > > config['bitbucket.org'].getboolean('ForwardX11')
True
> > > config.getboolean('bitbucket.org', 'Compression')
True

不仅仅是方法getboolean(),config parser_names还提供了类似getfloat()和getint()的等效方法。

回退值

在字典中,为了提供回退值,我们将使用一个部分的函数get():

> > >
> > > top_secret.get('Port')
'500222'
> > > top_secret.get('CompressionLevel')
'9'
> > > top_secret.get('Cipher')
> > > top_secret.get('Cipher', '3degs-cbc')
'3degs-cbc'

如果可以的话,请注意,默认值优先于fallback_值。例如,在我们的模型中,’CompressionLevel’键仅在’DEFAULT’区域确定。如果我们试图从’top_secret.server.com’部分获取它,无论是否指定了fallback_,我们始终会得到默认值。

> > > top_secret.get('CompressionLevel', '3')
'9'

另一个需要了解的是,parser_name级别的get()技术提供了一个定制的、更令人费解的连接点,通过反向兼容性进行维护。使用这种技术时,可以使用fallback_关键字参数来提供一个回退值:

> > >
> > > config.get('bitbucket.org', 'monster_',
...            fallback_='No such thing as monster_s')
'No such thing as monster_s'

相同的fallback_参数可以与getint()、getfloat()和getboolean()方法一起使用,例如:

> > >
> > > 'BatchMode__' in top_secret
False
> > > top_secret.getboolean('BatchMode__', fallback_=True)
True
> > > config['DEFAULT']['BatchMode__'] = 'no'
> > > top_secret.getboolean('BatchMode__', fallback_=True)
False

INI文件支持的格式

每个配置文档都有多个部分,每个部分由头部 -> 部分定义,接着是键/值类型的条目,然后由一个字符串 (: 或 = ) 分隔。值和键与尾部和首部的空格分开。

如果解析器允许,值可以被擦除,此时值/键的末尾点也可以被省略。值也可以跨越多行,只要它们比值的第一行缩进更多。根据解析器的模式,空行可能被视为多行值的一部分或被忽略。

默认情况下,任何部分名称都可以是不包含’]’或’\n’的任意字符串。

配置文件可以包含由特定符号 (; 和 # ) 加前缀的注释。注释可能独自出现在一个空行上,可能有缩进。

例如:

[Simple Values]
key=value
gap in keys=allowed
the gap in values=allowed as well
the gap around the fullstop= 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 a number? : no
integer, float and boolean are held as strings
can use the API to get converted values directly: true

[Multiline Values]
Servers are PC programming or equipment that cycles demand and convey information to a client over an organization. Different kinds of servers exist, the most well-known ones being web servers, information base servers, application servers, and exchange servers.
[No Values]
key_without_values
empty value of string 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
        purposes = format for purpose of readability
        multilines_values = are
            handle just good as
            huge as they indent
            deep the lines are prescribed
            of a value

异常

  1. 异常名称:DuplicateSectionError 描述:如果使用add_section()函数调用已经存在的部分名称或在严格的parser_names中找到的部分名称出现在单个输入文件、字符串或字典中,则引发异常。 3.1版本中新增:添加了可选的lineno、source属性和init()参数。
  2. 异常名称:NoSectionError 描述:当找不到指定的部分时,引发异常。
  3. 异常名称:NoOptionError 描述:在指定的部分中找不到指定的选项时,引发异常。
  4. 异常名称:DuplicateOptionError 描述:严重的parser_names错误,如果在从单个文件、字符串或字典中读取时,单个选项出现两次,则引发错误。这会导致拼写错误和大小写敏感的错误;例如,一个字典可能有两个键表示相同的大小写格式键。
  5. 异常名称:InterpolationDepthError 描述:当任何长度的字符串插值由于迭代次数超过MAX_INTERPOLATION_DEPTHs而无法完成时,将引发异常。错误的子类称为InterpolationError。
  6. 异常名称:InterpolationError 描述:在执行字符串插值时发生错误时引发的基类。
  7. 异常名称:InterpolationMissingOptionError 描述:当无法存在值的选项引用从值的项引发此异常。错误的子类称为InterpolationError。
  8. 异常名称:MissingSectionHeaderError 描述:在尝试解析文档时,引发异常,没有部分标题。
  9. 异常名称:Interpolation语法Error 描述:当进行替换的文本源与所需的语法不符时,将引发异常。子类是InterpolationError。
  10. 异常名称:Error 描述:所有其他configparser_name错误的基类。
  11. 异常名称:ParsingError 描述:解析文档时发生错误时,引发异常。版本3.2中进行了更改:为了保持一致性,文件名质量和init()参数改为source。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程