[英]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.