2

所以我试图在配置文件中使用字典来将报告名称存储到 API 调用中。所以是这样的:

report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}

我需要存储多个报告:apicalls 到一个配置值。我正在使用 ConfigObj。我已经阅读了那里的文档文档,它说我应该能够做到。我的代码看起来像这样:

from configobj import ConfigObj
config = ConfigObj('settings.ini', unrepr=True)
for x in config['report']:
    # do something... 
    print x

但是,当它遇到 config= 时,它会引发引发错误。我有点迷失在这里。我什至复制并粘贴了他们的示例和相同的内容,“引发错误”。我正在使用 python27 并安装了 configobj 库。

4

4 回答 4

4

如果您没有义务使用INI文件,则可以考虑使用更适合处理dict类似对象的另一种文件格式。查看您提供的示例文件,您可以使用JSON文件,Python 有一个内置模块来处理它。

例子:

JSON 文件“settings.json”:

{"report": {"/report1": "/https://apicall...", "/report2": "/https://apicall..."}}

Python代码:

import json

with open("settings.json") as jsonfile:
    # `json.loads` parses a string in json format
    reports_dict = json.load(jsonfile)
    for report in reports_dict['report']:
        # Will print the dictionary keys
        # '/report1', '/report2'
        print report
于 2016-07-03T03:04:58.407 回答
3

我在尝试读取 ini 文件时遇到了类似的问题:

[Section]
Value: {"Min": -0.2 , "Max": 0.2}

最终使用了配置解析器和 json 的组合:

import ConfigParser
import json
IniRead = ConfigParser.ConfigParser()
IniRead.read('{0}\{1}'.format(config_path, 'config.ini'))
value = json.loads(IniRead.get('Section', 'Value'))

显然可以使用其他文本文件解析器,因为 json 加载只需要 json 格式的字符串。我遇到的一个问题是字典/ json 字符串中的键需要用双引号引起来。

于 2017-06-20T13:12:55.977 回答
2

您的配置文件settings.ini应采用以下格式:

[report]
/report1 = /https://apicall...
/report2 = /https://apicall...

from configobj import ConfigObj

config = ConfigObj('settings.ini')
for report, url in config['report'].items():
    print report, url

如果你想使用unrepr=True,你需要

于 2016-07-03T01:19:08.900 回答
2

这个用作输入的配置文件很好:

report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}

此配置文件用作输入

flag = true
report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}

生成这个异常,看起来像你得到的:

O:\_bats>configobj-test.py
Traceback (most recent call last):
  File "O:\_bats\configobj-test.py", line 43, in <module>
    config = ConfigObj('configobj-test.ini', unrepr=True)
  File "c:\Python27\lib\site-packages\configobj.py", line 1242, in __init__
    self._load(infile, configspec)
  File "c:\Python27\lib\site-packages\configobj.py", line 1332, in _load
    raise error
configobj.UnreprError: Unknown name or type in value at line 1.

开启unrepr模式后,您需要使用有效的 Python 关键字。在我的示例中,我使用true而不是True. 我猜您的其他设置Settings.ini会导致异常。

unrepr 选项允许您使用配置文件存储和检索基本的 Python 数据类型。它必须使用与普通 ConfigObj 文件略有不同的语法。不出所料,它使用 Python 语法。这意味着列表是不同的(它们被方括号括起来),并且必须引用字符串。

unrepr 可以使用的类型是:

字符串、列表、元组
None、True、False
字典、整数、浮点数
和复数

于 2016-07-03T02:08:36.653 回答