Skip to main content

将行号信息添加到 ConfigParser 选项

项目描述

https://travis-ci.org/benfogle/configlines.svg?branch=master https://codecov.io/gh/benfogle/configlines/branch/master/graph/badge.svg

描述

该模块是 Python 标准configparser模块的扩展,它为每个存储的选项添加文件和行号信息。这主要用于报告错误消息:您可以将用户指向发生错误值的确切位置:

try:
    timeout = config.getint('connection', 'retry')
except ValueError:
    filename, line = config.get_location('connection', 'retry')
    logging.error("retry must be an integer (%s:%d)", filename, line)
    ...

这个包兼容 Python 2 和 3。

安装

使用 pip 安装:

$ pip install configlines

用法

给定以下两个配置文件:

# Line one of data1.cfg
[some_section]
foo = <s>1</s>

[DEFAULT]
bar = <s>2</s>
# Line one of data2.cfg
[some_section]
baz = <s>3</s>

您可以像标准模块一样阅读和操作它们:

>>> from configlines import ConfigParser
>>> cfg = ConfigParser()
>>> cfg.read(['data1.cfg', 'data2.cfg'])
>>> cfg.get('some_section', 'foo')
'1'

您还可以访问文件和行信息:

>>> cfg.get_location('some_section', 'foo')
('data1.cfg', 3)
>>> cfg.get_location('some_section', 'bar')
('data1.cfg', 6)
>>> cfg.get_location('some_section', 'baz')
('data2.cfg', 3)

除了get_location 之外,该模块还提供了get_lineget_filename函数以方便使用。

如果选项不是来自文件(即,您以编程方式设置它),则不会出现行号信息:

>>> cfg.set('some_section', 'qwerty', '1234')
>>> cfg.get_location('some_section', 'qwerty')
None

以编程方式覆盖选项将删除行号信息:

>>> cfg.get_location('some_section', 'foo')
('data1.cfg', 3)
>>> cfg.set('some_section', 'foo', '1234')
>>> cfg.get_location('some_section', 'foo')
None

行号信息可以显式设置:

>>> cfg.set('some_section', 'foo', '1234', location=('somefile.cfg',10))
>>> cfg.get_location('some_section', 'foo')
('somefile.cfg', 10)
>>> cfg.set('some_section', 'foo', '1234', location='preserve')
>>> cfg.get_location('some_section', 'foo')
('somefile.cfg', 10)
>>> cfg.set_location('some_section', 'foo', ('otherfile.cfg', 50))
>>> cfg.get_location('some_section', 'foo')
('otherfile.cfg', 50)

下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

configlines-0.3.tar.gz (6.1 kB 查看哈希

已上传 source

内置分布

configlines-0.3-py2.py3-none-any.whl (6.7 kB 查看哈希

已上传 py2 py3