遍历配置文件中的部分 [英] Iterate over sections in a config file

查看:196
本文介绍了遍历配置文件中的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我介绍了一下库的configparser。我将检查每个部分是否至少有一个布尔值设置为1。例如...

pre $ code $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ Large_Readout = 0

上面的代码会导致错误。

  [Vertical_Random_Readout_Size] 
Small_Readout = 0
Medium_Readout = 0
Large_Readout = 1

以上内容会通过。下面是我想到的一些伪代码...

  exit_test = False 
对于config_file中的部分:
section_check = False
作为parser.options(section)中的名称:
如果parser.getboolean(section,name):
section_check = True
if not section_check:
print错误:请在配置文件的{}部分指定一个设置.format(section)
exit_test = True
如果exit_test:
exit(1)

问题:
$ b $ 1第一个for循环并遍历配置文件的部分?

<2>这是做这个的好方法还是有更好的方法? (如果没有请回答问题一)。

解决方案

使用 ConfigParser 你必须解析你的配置。



解析后,您将获得所有使用 .sections() 方法。

可以遍历每个部分并使用 .items()

 用于conf.sections()中的each_section:
对于(each_key,each_val)在conf.items(each_section)中:
print each_key
print each_val


I recently go introduced to the library configparser. I would be to check if each section has at least one Boolean value set to one. For example...

[Horizontal_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 0

The above would cause an error.

[Vertical_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 1

The above would pass. Below is some pseudo code of what I had in mind...

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)

Questions:

1) How do I perform the first for loop and iterate over the sections of the config file?

2) Is this a good way of doing this or is there a better way? (If there isn't please answer question one.)

解决方案

Using ConfigParser you have to parse your config.

After parsing you will get all sections using .sections() method.

You can iterate over each section and use .items() to get all key/value pairs of each section.

for each_section in conf.sections():
    for (each_key, each_val) in conf.items(each_section):
        print each_key
        print each_val

这篇关于遍历配置文件中的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆