[英]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.