我需要存储Python应用程序的配置(键/值),我正在寻找将这些配置存储在文件中的最佳方法.
我遇到Python的ConfigParser,我想知道INI文件格式现在是否真的合适?!是否存在更新的格式或INI仍然是推荐的方式?(XML,JSON,...)
请分享您的意见/建议......
cod*_*ape 66
考虑使用普通的Python文件作为配置文件.
一个例子(example.conf):
# use normal python comments
value1 = 32
value2 = u"A unicode value"
value3 = "A plain string value"
value4 = ["lists", "are", "handy"]
value5 = {"and": "so", "are": "dictionaries"}
Run Code Online (Sandbox Code Playgroud)
在您的程序中,使用execfile(2.7 docs)加载配置文件:
if __name__ == "__main__":
config = {}
execfile("example.conf", config)
# python 3: exec(open("example.conf").read(), config)
print config["value1"]
print config["value5"]
Run Code Online (Sandbox Code Playgroud)
我喜欢这种方法,原因如下:
该方法被广泛使用,举几个例子:
execfile,它用于import读取/执行settings.pyAFAIK,但最终结果是相同的:执行设置文件中的代码.~/.bashrc在启动时读取并执行.site.py在启动时导入(并执行).字典也很受欢迎.基本上是一个哈希表.
{"one": 1, "two": 2} 是一个例子,有点像json.
然后你可以调用它mydict["one"],它会返回1.
然后你可以使用shelve将字典保存到文件中:
mydict = shelve.open(filename)
# then you can call it from there, like
mydict["one"]
Run Code Online (Sandbox Code Playgroud)
因此,它比ini文件更容易一些.你可以像列表一样添加内容或者很容易地更改选项,然后一旦你关闭它,它就会把它写回来.
下面是我的意思的简单例子:
import shelve
def main():
mydict = shelve.open("testfile")
mydict["newKey"] = value("some comment", 5)
print(mydict["newKey"].value)
print(mydict["newKey"].comment)
mydict.close()
class value():
def __init__(self, comment, value):
self.comment = comment
self.value = value
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
这完全取决于您的要求.如果(如你所说)你需要的只是键/值对,ini文件(或其他"普通"配置文件)将完全适合你.不,它们不会过时,因为它们仍在使用中.
如果您有分层结构并且还想使用更复杂的方法(例如:XML文件验证,命名空间等),XML/JSON是完美的.
这取决于配置文件的使用方式.
INI文件的一个优点是它们非常易于阅读和理解.如果手动编辑配置,在JSON或XML文件中出错会容易得多.PHP仍然使用INI文件.
但是,如果您的配置不是手动编辑,请使用您喜欢的任何格式,因为INI不是最容易解析的格式.