【发布时间】:2015-12-22 09:17:25
【问题描述】:
对于糟糕的标题,我深表歉意。如果我能够正确地描述我的问题,我会使用 google ;)
我发现了一段python代码能够将ini文件解析成一个名为“store”的python dict:
#!/usr/bin/env python
from ConfigParser import SafeConfigParser
def read(file, store):
def parse_maybe(section):
if not confp.has_section(section):
return False
if (section == "Main"):
for left, right in confp.items(section):
store[left] = right.format(**store)
return True
confp = SafeConfigParser()
confp.read(file)
parse_maybe("Main")
store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)
ini 文件可能包含带有占位符的声明,例如:
[Main]
output = {basedir}/somename.txt
运行代码时,{basedir} 会被 store 中已经定义的“/path/to/somewhere”替换。我猜这个魔力来自这行代码:
store[left] = right.format(**store)
我了解代码的作用。但我不明白如何 这是如何工作的。这个 ** 运算符对字典做了什么?非常感谢您提供指向教程等的指针。
【问题讨论】:
-
如果这不能解决您的查询,那么谷歌搜索“python 双星”会返回许多其他资源
-
**store 解压字典。如果函数接受关键字参数,并且关键字-值对在字典中,则可以使用 ** 将这些对传递给函数参数
-
@texasflood:这就是答案。谢谢。
标签: python dictionary configparser