Python 从配置文件中获取值的最佳方法是什么?
我想从配置文件中获取15个值,并将它们存储在单独的变量中 我正在使用Python 从配置文件中获取值的最佳方法是什么?,python,python-3.x,python-2.7,configparser,Python,Python 3.x,Python 2.7,Configparser,我想从配置文件中获取15个值,并将它们存储在单独的变量中 我正在使用 from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read(configFile) %(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
parser = SafeConfigParser()
parser.read(configFile)
%(nl)s to be a new line character so then when I get the value
message = parser.get(section, 'message', vars={'nl':'\n'})
这是一个非常好的图书馆
选项#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)
编辑:
下面是我尝试读取文件1并将所有值存储在dict中,然后尝试使用这些值。
我有一个多行字符串,我正在使用
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read(configFile)
%(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"]
作为一种可能的解决办法:
module_variables = globals() # represents the current global symbol table
for name in ('one', 'two'):
module_variables[name] = parser.get(section, name)
print one, two
作为一种可能的解决办法:
module_variables = globals() # represents the current global symbol table
for name in ('one', 'two'):
module_variables[name] = parser.get(section, name)
print one, two
一个解决方案是使用字典和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"]
一个解决方案是使用字典和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"]
要以dict形式从单个节获取值,请执行以下操作:
options = dict(parser.items(section))
您可以像往常一样访问单个值:选项[“一”]
,选项[“两”]
。在Python 3.2+configparser中,configparser本身提供类似dict的访问
为了灵活性,支持从各种源格式更新配置和/或集中配置管理;您可以定义封装对配置变量的解析/访问的自定义类,例如:
class Config(object):
# ..
def update_from_ini(self, inifile):
# read file..
self.__dict__.update(parser.items(section))
在本例中,单个值可作为实例属性使用:
config.one
,config.two
,以dict形式从单个节获取值:
options = dict(parser.items(section))
您可以像往常一样访问单个值:选项[“一”]
,选项[“两”]
。在Python 3.2+configparser中,configparser本身提供类似dict的访问
为了灵活性,支持从各种源格式更新配置和/或集中配置管理;您可以定义封装对配置变量的解析/访问的自定义类,例如:
class Config(object):
# ..
def update_from_ini(self, inifile):
# read file..
self.__dict__.update(parser.items(section))
在本例中,单个值可以作为实例属性使用:
config.one
,config.two
。@siecje,文档声明不应修改局部变量()的结果,但globals()的技巧也可以,尽管这将是模块范围。@siecje,文档声明局部变量()的结果()不应该被修改,但是globals()的技巧虽然这是模块作用域,但它也可以工作。为什么它同时标记了python-3.x和python-2.7?您需要编写在这两种情况下都可以工作的代码吗?为什么它同时标记了python-3.x和python-2.7?您需要编写在这两种情况下都可以工作的代码吗?您还可以使用它在2.x中获取3.2+模块。因此,我应该从配置文件f中读取所有的值将文件转换为dict,然后将每个变量名设置为dict[name],然后我只打开并读取配置文件一次,好的,我会尝试that@Siecje:如果使用dict只是将每个值放入一个单独的变量中,那么创建dict是没有意义的。您可以使用:get=functools.partial(parser.get,section)
然后调用get(“一”)
如果您坚持使用单独的变量。尽管为了可读性和可维护性,最好使用一个dict/自定义对象来访问配置,而不是15个单独的变量。我已经更新了我的代码,尝试实现它,但我正在使用替换,以便在消息中使用换行符。您还可以使用2.x中的3.2+模块,因此我应该将配置文件中的所有值读入一个dict,然后将每个变量名设置为dict[name]然后我只打开并读取配置文件一次,好的,我会尝试that@Siecje:如果使用dict只是将每个值放入一个单独的变量中,那么创建dict是没有意义的。您可以使用:get=functools.partial(parser.get,section)
然后调用get(“one”)
如果您坚持使用单独的变量。尽管为了可读性和可维护性,最好使用单个dict/自定义对象来访问配置,而不是使用15个单独的变量。我已经更新了我的代码以尝试实现它,但我正在使用替换,以便在消息中使用换行符。