在Python中使用设置文件的最佳做法是什么? [英] What's the best practice using a settings file in Python?
问题描述
我有一个运行有很多参数的命令行脚本.现在到了我有太多参数的地步,我也想以字典形式有一些参数.
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.
一些需求":
- 我希望它不是一个简单易懂的文本文件,而不是使用
pickle
. - 我希望能够在其中添加类似字典的数据,即应支持某种形式的嵌套.
一个简化的伪示例文件:
A simplified pseudo example file:
truck:
color: blue
brand: ford
city: new york
cabriolet:
color: black
engine:
cylinders: 8
placement: mid
doors: 2
推荐答案
您可以有一个常规的Python模块,例如config.py,如下所示:
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,
)
并像这样使用它:
import config
print config.truck['color']
这篇关于在Python中使用设置文件的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!