2012-12-11 55 views
4

我正在尋找一種方法來使用在ini文件中加載到Logging.config.FileConfig時在configparser庫中找到的ExtendedInterpolation功能。與Logging.Config.FileConfig一起使用ExtendedInterpolation

http://docs.python.org/3/library/configparser#configparser.ExtendedInterpolation

所以,如果我有一個ini文件看起來像這樣:

[logSettings] 
eventlogs=application 
logfilepath=C:\Programs\dk_test\results\dklog_009.log 
levelvalue=10 

[formatters] 
keys=dkeventFmt,dklogFmt 

[handlers] 
keys=dklogHandler 

[handler_dklogHandler] 
class=FileHandler 
level=${logSettings:levelvalue} 
formatter=dklogFmt 
args=(${logSettings:logfilepath}, 'w') 

[logger_dklog] 
level=${logSettings:levelvalue} 
handlers=dklogHandler 

正如你看到的,我通過使用$ {...}符號來繼擴展插語法在不同部分中引用一個值。當像這樣調用文件logging.config.fileConfig(filepath)時,模塊內的評估總是失敗。尤其是在部分的參數選項的評估中。

有沒有辦法解決這個問題?謝謝!

注:使用Python 3.2

回答

1

決定使用武力過該文件的插值並將結果保存到其他臨時文件。我使用臨時文件作爲logconfig。

功能如下:

tmpConfigDict   = {} 
tmpConfig    = ConfigParser(allow_no_value = True, 
          interpolation = ExtendedInterpolation()) 
for path in configPaths: 
    tmpConfig.read(path) 

#Iterate over options and use "get()" to execute the Interpolation 
for sec in tmpConfig.sections(): 
    tmpConfigDict[sec] = {} 
    for opt, _ in tmpConfig[sec].items(): 
     tmpConfigDict[sec][opt] = cleanValue(tmpConfig.get(sec, opt)) 

#Finished getting values. Write the dict to the configparser 
tmpConfig.read_dict(tmpConfigDict) 

#Open the file handle and close it when done 
with open(pathToTmpFile, 'w') as fp: 
    tmpConfig.write(fp, space_around_delimiters = False)