使用python的字典配置文件

2024-10-01 17:27:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我需要存储多个报告:apicall到一个配置值。我正在使用ConfigObj。我在那里读过documentationdocumentation,上面说我应该能做到。我的代码如下:

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

但是,当它点击config=时会抛出一个raise错误。我有点迷路了。我甚至复制粘贴了他们的例子和同样的东西,“引发错误”。我正在使用python27并安装configobj库。


Tags: httpsreport名称apiconfig字典报表documentation
3条回答

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

示例:

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

配置文件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,则需要

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

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中还有一些其他设置导致了异常。

The unrepr option allows you to store and retrieve the basic Python data-types using config files. It has to use a slightly different syntax to normal ConfigObj files. Unsurprisingly it uses Python syntax. This means that lists are different (they are surrounded by square brackets), and strings must be quoted.

The types that unrepr can work with are :

strings, lists, tuples
None, True, False
dictionaries, integers, floats
longs and complex numbers

相关问题 更多 >

    热门问题