c00*_*ter 308 python settings configuration parsing yaml
我有一个命令行脚本,我运行了很多参数.我现在已经到了一个我有太多参数的地方,我想也有一些字典形式的参数.
因此,为了简化操作,我希望使用设置文件来运行脚本.我真的不知道用什么库来解析文件.这样做的最佳做法是什么?我当然可以自己敲一些东西,但是如果有一些库,那我就是耳朵.
一些"要求":
pickle我希望它是一个可以轻松阅读和编辑的直接文本文件.一个简化的伪示例文件:
truck:
color: blue
brand: ford
city: new york
cabriolet:
color: black
engine:
cylinders: 8
placement: mid
doors: 2
Run Code Online (Sandbox Code Playgroud)
dug*_*res 203
你可以有一个常规的Python模块,比如config.py,就像这样:
truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
import config
print config.truck['color']
Run Code Online (Sandbox Code Playgroud)
Ben*_*son 153
您提供的示例配置实际上是有效的YAML.事实上,YAML满足您的所有要求,以大量语言实施,并且非常人性化.我强烈建议你使用它.该PyYAML项目提供了一个很好的Python模块,实现YAML.
使用yaml模块非常简单:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
Run Code Online (Sandbox Code Playgroud)
Mav*_*les 89
我发现这是最有用和易于使用的 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
Run Code Online (Sandbox Code Playgroud)
并检索如下数据:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
Ano*_*oop 52
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}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
237941 次 |
| 最近记录: |