2011-06-19 58 views
2

是否有解析器讀取並存儲要寫入的數據類型? 文件格式必須產生可讀。 貨架不提供。Python ini解析器

+2

[ConfigParser(http://docs.python.org/library/configparser.html) –

+0

不ConfigParser不是你想要的嗎? –

+0

我需要支持自動類型檢測。 ConfigParser以字符串形式讀取所有內容。 – Evgeny

回答

1

使用ConfigParser類ini文件格式讀取配置文件:

http://docs.python.org/library/configparser.html#examples

INI文件格式不存儲存儲的值的數據類型(你需要知道他們爲你讀數據返回)。您可以通過JSON格式編碼的值克服這個限制:

import simplejson 
from ConfigParser import ConfigParser 

parser = ConfigParser() 
parser.read('example.cfg') 

value = 123 
#or value = True 
#or value = 'Test' 

#Write any data to 'Section1->Foo' in the file: 
parser.set('Section1', 'foo', simplejson.dumps(value)) 

#Now you can close the parser and start again... 

#Retrieve the value from the file: 
out_value = simplejson.loads(parser.get('Section1', 'foo')) 

#It will match the input in both datatype and value: 
value === out_value 

作爲JSON,存儲值的格式是人類可讀。

+0

我需要一個解析器,它在讀取記錄類型時自動檢測。 – Evgeny

+0

ConfigParser以字符串形式讀取所有內容。 – Evgeny

+0

然後以json格式存儲字符串,以便您可以讀取類型? –

0

你可以使用下面的函數

def getvalue(parser, section, option): 
    try: 
     return parser.getint(section, option) 
    except ValueError: 
     pass 
    try: 
     return parser.getfloat(section, option) 
    except ValueError: 
     pass 
    try: 
     return parser.getbool(section, option) 
    except ValueError: 
     pass 
    return parser.get(section, option) 
+0

如果您存儲布爾值(存儲在ini文件中的值爲1或0),則會返回一個int值。 –

+0

這是一個重要的限制,是的。不幸的是,當時不可能找出確切的含義。 (就像很多可能的值一樣)。幸運的是,如果你像使用它那樣使用它,那麼它就不會成爲一個問題,如:如果getvalue(parser,「asection」,「boollookslikeint」):' – Robin

+0

最終,如果OP只是以ini文件格式存儲東西 - 沒有進一步的元數據,能夠返回數據類型。 –

0

隨着configobj庫,它變得非常簡單。現在

import sys 
import json 
from configobj import ConfigObj 

if(len(sys.argv) < 2): 
    print "USAGE: pass ini file as argument" 
    sys.exit(-1) 

config = sys.argv[1] 
config = ConfigObj(config) 

可以使用config作爲一個字典中提取所需的配置。

如果您想將其轉換爲json,那也很簡單。

config_json = json.dumps(config) 
print config_json