在Python中使用设置文件的最佳做法是什么?[关闭]

问题:在Python中使用设置文件的最佳做法是什么?[关闭]

我有一个运行有很多参数的命令行脚本。现在到了我有太多参数的地步,我也想以字典形式有一些参数。

因此,为了简化操作,我想使用设置文件来运行脚本。我真的不知道该使用什么库来解析文件。最佳做法是什么?我当然可以自己动手做一些事情,但是如果有图书馆可以帮助我,我会不胜枚举。

一些“需求”:

  • 与其使用pickle我,我不希望它是一个易于阅读和编辑的简单文本文件。
  • 我希望能够在其中添加类似字典的数据,即应支持某种形式的嵌套。

简化的伪示例文件:

truck:
    color: blue
    brand: ford
city: new york
cabriolet:
    color: black
    engine:
        cylinders: 8
        placement: mid
    doors: 2

I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too.

So in order to simplify things I would like to run the script with a settings file instead. I don’t really know what libraries to use for the parsing of the file. What’s the best practice for doing this? I could of course hammer something out myself, but if there is some library for this, I’m all ears.

A few ‘demands’:

  • Rather than using pickle I would like it to be a straight forward text file that can easily be read and edited.
  • I want to be able to add dictionary-like data in it, i.e., some form of nesting should be supported.

A simplified pseudo example file:

truck:
    color: blue
    brand: ford
city: new york
cabriolet:
    color: black
    engine:
        cylinders: 8
        placement: mid
    doors: 2

回答 0

您可以有一个常规的Python模块,例如config.py,如下所示:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

并像这样使用它:

import config
print config.truck['color']  

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print config.truck['color']  

回答 1

您提供的样本配置实际上是有效的YAML。实际上,YAML可以满足您的所有需求,并以多种语言实现,并且非常人性化。我强烈建议您使用它。该PyYAML项目提供了一个很好的Python模块,实现YAML。

使用yaml模块非常简单:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

回答 2

我发现这是最有用和易于使用的 https://wiki.python.org/moin/ConfigParserExamples

您只需创建一个“ myfile.ini”,例如:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

并像这样检索数据:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

I Found this the most useful and easy to use https://wiki.python.org/moin/ConfigParserExamples

You just create a “myfile.ini” like:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

And retrieve the data like:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

回答 3

Yaml和Json是存储设置/配置的最简单,最常用的文件格式。PyYaml可用于解析yaml。Json已经从2.5开始成为python的一部分。Yaml是Json的超集。Json将解决大多数使用情况,但需要转义的多行字符串除外。Yaml也会处理这些情况。

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}