【问题标题】:What is the best way to get values from a config file? [closed]从配置文件中获取值的最佳方法是什么? [关闭]
【发布时间】:2013-02-04 21:09:08
【问题描述】:

我想从配置文件中获取 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?您是否需要编写同时适用于两者的代码?

标签: python python-3.x python-2.7 configparser


【解决方案1】:

从单个部分获取值作为字典:

options = dict(parser.items(section))

您可以像往常一样访问单个值:options["one"]、options["two"]。在 Python 3.2+ 中,configparser 自己提供类似 dict 的访问。

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

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

在这种情况下,单个值可用作实例属性:config.one、config.two。

【讨论】:

  • 也可以使用configparser获取2.x中的3.2+模块。
  • 所以我应该将配置文件中的所有值读入一个字典,然后设置每个变量 name = dict[name] 然后我只打开并读取一次配置文件,好的,我会的试试看
  • @Siecje:如果您只使用字典将每个值放入单独的变量中,那么创建字典是没有意义的。如果您坚持使用单独的变量,您可以使用:get = functools.partial(parser.get, section) 并稍后调用 get("one")。尽管为了可读性和可维护性,最好使用单个 dict/custom 对象来访问配置,而不是使用 15 个单独的变量。
  • 我已经更新了我的代码以尝试实现它,但我正在使用替换,以便我可以在我的消息中包含换行符。
【解决方案2】:

解决方案也可以使用字典和 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】:

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

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

    【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2010-09-08
    相关资源
    最近更新 更多