在Python中使用设置文件的最佳实践是什么?
我有一个命令行脚本,运行时需要输入很多参数。现在参数太多了,我想把一些参数用字典的形式来处理。
为了简化操作,我想用一个设置文件来运行这个脚本。可是我不太清楚该用什么库来解析这个文件。有什么好的做法吗?当然,我可以自己写一个,但如果有现成的库可以用,那我很乐意听听。
我有几个“要求”:
- 我希望使用一个简单的文本文件,而不是用
pickle
,这样更容易阅读和编辑。 - 我想在文件中添加类似字典的数据,也就是说,应该支持某种形式的嵌套。
下面是一个简化的伪代码示例文件:
truck:
color: blue
brand: ford
city: new york
cabriolet:
color: black
engine:
cylinders: 8
placement: mid
doors: 2
4 个回答
181
我觉得这个链接最有用,而且使用起来很简单: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 # For Python 3 use the configparser module instead (all lowercase)
>>> 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'
284
你可以有一个普通的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'])