我最近接触到了 configparser 库。我希望能够检查每个部分是否至少有一个布尔值设置为 1。例如:
[Horizontal_Random_Readout_Size]
Small_Readout = 0
Medium_Readout = 0
Large_Readout = 0
上面的情况会导致错误。
[Vertical_Random_Readout_Size]
Small_Readout = 0
Medium_Readout = 0
Large_Readout = 1
上面的就过去了。下面是我想到的一些伪代码:
exit_test = False
for sections in config_file:
section_check = False
for name in parser.options(section):
if parser.getboolean(section, name):
section_check = True
if not section_check:
print "ERROR:Please specify a setting in {} section of the config file".format(section)
exit_test = True
if exit_test:
exit(1)
问题:
1) 如何执行第一个 for 循环并迭代配置文件的各个部分?
2)这是这样做的好方法还是有更好的方法? (如果没有,请回答问题一。)
Using ConfigParser http://docs.python.org/2/library/configparser.html你必须解析你的配置。
解析后,您将使用以下命令获取所有部分.sections() http://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.sections method.
您可以迭代每个部分并使用.items() http://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.items获取每个部分的所有键/值对。
for each_section in conf.sections():
for (each_key, each_val) in conf.items(each_section):
print each_key
print each_val
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)