2016-07-03 52 views
1

所以我想使用一個配置文件內的字典存儲報告名稱的API調用。所以像這樣:配置文件與使用Python的字典

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

我需要存儲多個報告:apicalls一個配置值。我正在使用ConfigObj。我已經閱讀documentationdocumentation,它說我應該能夠做到這一點。我的代碼看起來像這樣:

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

但是,當它命中config =它會拋出一個引發錯誤。我有點迷失在這裏。我甚至複製並粘貼他們的例子和相同的東西,「引發錯誤」。我正在使用python27並安裝了configobj庫。

+0

正在拋出哪個錯誤?你可以在這裏粘貼完整的堆棧跟蹤嗎? –

回答

1

您的配置文件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,你需要

1

用作輸入此配置文件是罰款:

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可以處理的類型是:

字符串,列表,元組
無,真,假
詞典,整型,浮點
多頭和複數

2

如果您'沒有義務使用INI文件,您可以考慮使用另一種更適合處理類似於dict的對象的文件格式。看看你給出的示例文件,你可以使用JSON文件,Python有一個built-in模塊來處理它。

示例:

JSON文件「設置。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 
0

我有一個類似的問題,試圖讀取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')) 

顯然其他文本文件pa rsers可以用作json加載只需要json格式的字符串。我遇到的一個問題是字典/ json字符串中的鍵需要用雙引號引起來。