English 中文(简体)
掩饰材料: 任何档案格式建议? 定义格式仍然适当? 弃婴学校
原标题:Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school
  • 时间:2011-11-22 11:21:08
  •  标签:
  • python

我需要储存用于“灰色”用途的配置(关键/价值),我正在寻找最佳方式将这些配置存放在档案中。

I run into Python s ConfigParser and I wondered if the INI file format is really still appropriate nowadays?! Does there exist a more up-to-date format or is INI still the recommended way to go? (XML, JSON, ...)

请分享您的意见/建议......

最佳回答

考虑将便衣档案作为配置文件。

例如(config.py):

# use normal python comments

value1 = 32
value2 = "A string value"

value3 = ["lists", "are", "handy"]
value4 = {"and": "so", "are": "dictionaries"}

在您的节目中,用exec装上书面文件():

from pathlib import Path

if __name__ == "__main__":
    config = {}
    exec(Path("config.py").read_text(encoding="utf8"), {}, config)
    
    print(config["value1"])
    print(config["value4"])

我赞同这种做法,原因如下:

  • In the simple case, the format is as easy to author as an INI-style config file. It also shares an important characteristic with INI files: it is very suitable for version control (this is less true for XML and maybe also for JSON)
  • I like the flexibility that comes with having the config file in an actual programming language.

这种办法得到广泛使用,有几个例子:

  • A Django site s settings lives inside settings.py. Django does not use execfile, it uses import to read/execute settings.py AFAIK, but the end result is the same: the code inside the settings file is executed.
  • The bash shell reads and executes ~/.bashrc on startup.
  • The Python interpreter imports site.py on startup.
问题回答

INI完全是至于科索沃,正如其他发言者一样,你的汇卷格式确实取决于你如何使用。

我本人是:简明、可读、灵活。

谷歌似乎赞同我的热情,因为在谷歌应用引擎中也使用了这种热情。 The python parser is

这完全取决于你的要求。 如果(如你所说)你的所有需要都是关键/价值乳制品,那么,内部档案(或其他“解释”文件)将完全适合你。 他们没有过期,因为他们仍在使用。

XML/JSON is perfect if you have hierarchical structures and also want to use more sophisticated methods (e.g: XML file validation, namespaces, etc.).

www.un.org/Depts/DGACM/index_spanish.htm 这取决于如何使用没收档案。

尼共(INI)文件的优势之一是,它们确实容易阅读和理解。 如果你亲手conf,在JSON或XML档案中犯错,会更容易。 PHP仍然使用NINI文档。

然而,如果您的议事工作不是要经过手头编辑的话,就与你一样,因为尼佛并不是最容易的。

为了完整起见,你还可以在“shlex”模块的帮助下,使用一种彩票式组合格式。 如果你有一套固定的组合参数,那么你可以将其与“optparse”模块结合起来。

from optparse import OptionParser
_o = OptionParser("%prog [options] configfiles...")
_o.add_option("--hostname", metavar="HOSTNAME", default="10.0.0.1")
_o.add_option("--username", metavar="USERNAME", default="admin")
_o.add_option("--password", metavar="PASSWORD", default="admin")

import shlex
def parse(filename, defaults):
    opt, args = _o.parse_args(shlex.split(open(filename).read()), defaults)
    return opt

if __name__ == "__main__":
    import sys
    values, args = _o.parse_args()
    for arg in args:
       values = parse(arg, values)
    values, args = _o.parse_args(values = values)
    for name in _o.defaults:
        print name, "=", getattr(values, name)

例子表明,如果存在一套缺省价值和用户界定的红利,你如何掌握内部档案。 因此,假定你有两件档案,包括:

档案1.ini:

--hostname 10.2.3.4
--password admin-sc

档案2.ini:

--username "foo bar"
--password "special key"

然后,您可操作/configtest.py file1.ini file2.ini—password other,由此得出的数值为10.2.3.4,用户名为“foo bar”,密码为“other”。 如果你已经对你的方案参数进行了选择,那么这种配置环境的改变是手无寸铁的;它只是重复使用,而且你可以把指挥线的价值观从一个汇合档案中,甚至可能有一些全球汇合环境。

作为奖励措施,你的配置参数总是有文件记载,错误的配置参数将尽早出现,正如你可以利用选择的分离来预先检查你的缺省环境档案(ema)。 作为下游,内部没有意见,配置内容不容易地进行分化。 你们的教区基本上是一线。

我不止一次遇到同样的问题。 我爱护假档案,把它作为环境档案,它只是简明、简便的,也是像它一样的所有 p子。 不能真正相信外来文件的想法的好时机。

因此,我接着创建了Converge

它支持一些先进选择,但核心是作为环境档案的简便餐模块。

简单

  • creating default_settings.py, prod_settings.py
  • pip install converge
  • import settings




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...