我有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"]
这是为什么标记python-3.x和python-2.7?你需要编写在两者都有效的代码吗? – abarnert