从配置文件获取值的最佳方法是什么?

-1 投票
3 回答
7881 浏览
提问于 2025-04-17 14:45

我有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"]

3 个回答

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
1

一个解决方案是使用字典和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"]
3

要从一个部分获取值并把它们放进一个字典里,可以这样做:

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

撰写回答