2013-02-04 106 views
0

我有15个值,我想从配置文件中获取并将它们存储在单独的变量中。从配置文件获取值的最佳方式是什么?

我使用

from ConfigParser import SafeConfigParser 

parser = SafeConfigParser() 
parser.read(configFile) 

,这是一个非常好的图书馆。

选项#1

如果我改变变量的名称,并希望它相匹配的配置文件条目我不得不修改相应的行中的函数

def fromConfig(): 
    #open file 
    localOne = parser.get(section, 'one') 
    localTwo = parser.get(section, 'two') 
    return one, two 

one = '' 
two = '' 
#etc 
one, two = fromConfig() 

选项# 2

查看变量从哪里得到它们的值更清晰,但随后我会打开和关闭每个变量的文件

def getValueFromConfigFile(option): 
    #open file 
    value = parser.get(section, option) 
    return value 

one = getValueFromConfigFile("one") 
two = getValueFromConfigFile("two") 

选项#3

这一次并没有太大的意义,因为我有我的所有变量名的另一份名单,但功能更干净。

def getValuesFromConfigFile(options): 
    #open file 
    values = [] 
    for option in options: 
     values.append(parser.get(section, option)) 

    return values 

one = '' 
two = '' 
configList = ["one", "two"] 
one, two = getValuesFromConfigFile(configList) 

编辑: 这是我在阅读文件之一,并存储在字典的所有值,然后试图用他看重的尝试。 我有一个多行字符串,我使用

%(nl)s to be a new line character so then when I get the value 
message = parser.get(section, 'message', vars={'nl':'\n'}) 

这里是我的代码:

from ConfigParser import SafeConfigParser 

def getValuesFromConfigFile(configFile): 
    ''' reads a single section of a config file as a dict ''' 
    parser = SafeConfigParser() 
    parser.read(configFile) 
    section = parser.sections()[0] 

    options = dict(parser.items(section)) 

    return options 


options = getValuesFromConfigFile(configFile) 

one = options["one"] 
+0

这是为什么标记python-3.x和python-2.7?你需要编写在两者都有效的代码吗? – abarnert

回答

0

作为一个可能的解决方案:

module_variables = globals() # represents the current global symbol table 
for name in ('one', 'two'): 
    module_variables[name] = parser.get(section, name) 
print one, two 
+0

什么是当地人()? – Siecje

+0

@siecje,http://docs.python.org/2/library/functions.html#locals – newtover

+0

文档指出locals()的结果不应该被修改,但是globals()的技巧确实有效同样,尽管这将是模块范围。 – newtover

0

一个解决办法是为很好地使用字典& json可以使事情变得容易&可重复使用

import json 

def saveJson(fName, data): 
    f = open(fName, "w+") 
    f.write(json.dumps(data, indent=4)) 
    f.close() 

def loadJson(fName): 
    f = open(fName, "r") 
    data = json.loads(f.read()) 
    f.close() 
    return data 

mySettings = { 
    "one": "bla", 
    "two": "blabla" 
} 

saveJson("mySettings.json", mySettings) 
myMoadedSettings = loadJson("mySettings.json") 

print myMoadedSettings["two"] 
2

从单节作为一个字典中获取值:

options = dict(parser.items(section)) 

您可以访问单个值和往常一样:options["one"]options["two"]。在Python 3.2+中,configparser本身提供类似字典的访问。

为了灵活性,支持从各种源格式更新配置和/或集中配置管理;你可以定义一个封装解析自定义类/访问配置变量例如为:

class Config(object): 
    # ..  
    def update_from_ini(self, inifile): 
     # read file.. 
     self.__dict__.update(parser.items(section)) 

个体值可作为实例在这种情况下属性:config.oneconfig.two

+1

您也可以使用['configparser'](http://pypi.python.org/pypi/configparser/3.3.0r2)获取2.x中的3.2+模块。 – abarnert

+0

所以我应该读取配置文件中的所有值转换为字典,然后设置每个变量 name = dict [name] 然后我只打开并读取配置文件一次,好吧我会尝试 – Siecje

+0

@Siecje:如果仅用它来将每个值放入一个单独的变量中,则没有必要创建一个字典。如果你坚持使用单独的变量,你可以使用:get = functools.partial(parser.get,section),然后调用get(“one”)。尽管为了可读性和可维护性,最好使用单个字典/自定义对象来访问配置,而不是15个单独的变量。 – jfs

相关问题