简体   繁体   English

使用python的字典配置文件

[英]config file with a dictionary using python

So I am trying to use a dictionary inside a config file to store a report name to an API call. 因此,我试图在配置文件中使用字典来将报告名称存储到API调用中。 So something like this: 所以像这样:

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

I need to store multiple reports:apicalls to one config value. 我需要存储多个report:apicalls到一个配置值。 I am using ConfigObj. 我正在使用ConfigObj。 I have read there documentation , documentation and it says I should be able to do it. 我读过那里的文档文档说我应该可以做到。 My code looks something like this: 我的代码如下所示:

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

However when it hits the config= it throws a raise error. 但是,当它达到config =时,会引发加注错误。 I am kinda lost here. 我有点迷路了。 I even copied and pasted their example and same thing, "raise error". 我什至复制并粘贴了他们的示例和同一件事,“引发错误”。 I am using python27 and have the configobj library installed. 我正在使用python27并安装了configobj库。

If you're not obligated to use INI files, you might consider using another file format more suitable to handle dict -like objects. 如果您没有义务使用INI文件,则可以考虑使用另一种更适合处理dict的对象的文件格式。 Looking at the example file you gave, you could use JSON files, Python has a built-in module to handle it. 查看给出的示例文件,您可以使用JSON文件,Python有一个内置模块来处理它。

Example: 例:

JSON File "settings.json": JSON文件“ settings.json”:

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

Python code: 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

Your config file settings.ini should be in following format: 您的配置文件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

If you want to use unrepr=True , you need to 如果要使用unrepr=True ,则需要

This config file used as input is fine: 这个配置文件可以用作输入:

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

This config file used as input 此配置文件用作输入

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

generates this exception, which looks like what you are getting: 生成此异常,看起来像您得到的:

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.

With the unrepr mode set on, you are required to use valid Python keywords. unrepr模式后,您需要使用有效的Python关键字。 In my example I used true instead of True . 在我的示例中,我使用true而不是True I'm guessing you have some other settings in your Settings.ini which are causing the exception. 我猜您在Settings.ini中还有其他一些设置会导致异常。

The unrepr option allows you to store and retrieve the basic Python data-types using config files. unrepr选项允许您使用配置文件存储和检索基本的Python数据类型。 It has to use a slightly different syntax to normal ConfigObj files. 它必须使用与普通ConfigObj文件略有不同的语法。 Unsurprisingly it uses Python syntax. 毫不奇怪,它使用Python语法。 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 : unrepr可以使用的类型是:

strings, lists, tuples 字符串,列表,元组
None, True, False 无,正确,错误
dictionaries, integers, floats 字典,整数,浮点数
longs and complex numbers 长和复数

I had a similar issue trying to read ini file: 我在尝试读取ini文件时遇到了类似的问题:

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

Ended up using a combination of config parser and json: 最终使用了配置解析器和json的组合:

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

Obviously other text file parsers can be used as the json load only requires a string in the json format. 显然,可以使用其他文本文件解析器,因为json加载仅需要json格式的字符串。 One issue I did run into was the keys in the dictionary/ json string need to be in double quotes. 我遇到的一个问题是字典/ json字符串中的键必须用双引号引起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM