![](/img/trans.png)
[英]Adding new section in config file without overwriting it using ConfigParser
[英]How to skip a section in config file using configparser
我写了一个代码,其中参数是从配置文件中获取的。 我在配置中的第一个参数是用于设置调试级别。
config = ConfigParser.RawConfigParser()
config.read('config.cfg')
log_level = config.get('Logger','log_level' )
配置中还有其他部分,提供了用于扫描每个部分的服务器IP和密码。
主要代码:
for section in config.sections():
components = dict() #start with empty dictionary for each section
env.user = config.get(section, 'server.user_name')
env.password = config.get(section, 'server.password')
host = config.get(section, 'server.ip')
从我的配置
[Logger]
#Possible values for logging are INFO, DEBUG and ERROR
log_level = DEBUG
[server1]
server.user_name = root
server.password = password
server.ip = 172.19.41.21
[server2]
server.user_name = root
server.password = password
server.ip = 172.19.41.21
现在,我的代码说要检查每个部分以检索用户名和密码。 由于第一部分不包含这些值,因此失败了。 我该如何检查每个部分的用户名和密码,如果没有,请转到下一部分。 我尝试检查“无”,然后转到下一部分。 但是那个代码很难看,而且失败了。 像这样:
if env.user=='':
next
有人可以帮我进一步吗?
将此代码添加到for
循环的开头:
if not config.has_option(section, 'server.user_name'):
continue
由于只有第一部分不包含这些值,因此可以使用iter
函数。
sections = iter(config.sections())
next(sections)
for section in sections:
# something(section)
或@tjohnson提到:
for section in config.sections()[1:]:
# something(section)
另一种方法是仅捕获异常。
for section in config.sections():
components = dict() #start with empty dictionary for each section
try:
env.user = config.get(section, 'server.user_name')
env.password = config.get(section, 'server.password')
host = config.get(section, 'server.ip')
except ConfigParser.NoOptionError as e:
continue # At least one required option is missing in the section, skip
优点是,如果缺少任何选项,则将忽略该部分。
但是,如果您需要具有原子性(例如,如果由于server.ip
不存在而最终忽略了该节,则设置env.user
是一个问题),则可能需要这样的内容。
for section in config.sections():
components = dict() #start with empty dictionary for each section
try:
tmp_user = config.get(section, 'server.user_name')
tmp_password = config.get(section, 'server.password')
tmp_host = config.get(section, 'server.ip')
except ConfigParser.NoOptionError as e:
continue # At least one required option is missing in the section, skip
else:
env.user = tmp_user
env.password = tmp_password
host = tmp_host
在这种情况下,使用has_option
3次可能会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.