[英]config file with a dictionary using python
因此,我试图在配置文件中使用字典来将报告名称存储到API调用中。 所以像这样:
report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
我需要存储多个report:apicalls到一个配置值。 我正在使用ConfigObj。 我读过那里的文档 , 文档说我应该可以做到。 我的代码如下所示:
from configobj import ConfigObj
config = ConfigObj('settings.ini', unrepr=True)
for x in config['report']:
# do something...
print x
但是,当它达到config =时,会引发加注错误。 我有点迷路了。 我什至复制并粘贴了他们的示例和同一件事,“引发错误”。 我正在使用python27并安装了configobj库。
如果您没有义务使用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
您的配置文件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
中还有其他一些设置会导致异常。
unrepr选项允许您使用配置文件存储和检索基本的Python数据类型。 它必须使用与普通ConfigObj文件略有不同的语法。 毫不奇怪,它使用Python语法。 这意味着列表是不同的(它们用方括号括起来),并且字符串必须用引号引起来。
unrepr可以使用的类型是:
字符串,列表,元组
无,正确,错误
字典,整数,浮点数
长和复数
我在尝试读取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字符串中的键必须用双引号引起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.