[英]Python ConfigParser: input section name as variable
我想从.cnf文件中读取数据。 它可能有很多部分,所以我想自动读出它们。 我的代码如下所示:
while numberOfSections > 0:
check = parser.get(numberOfSections, "check")
hostname = parser.get(numberofSections, "hostname")
ip = parser.get(numberofSections, "IP")
port = parser.get(numberofSections, "port")
request = parser.get(numberofSections, "request")
现在不幸的是,它只说“无节:5”。 在此示例中,我的numberofSections变量为5,仅此而已。 这些部分的名称如下:
[1]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
[2]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
[3]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
...
那么,有什么想法吗? 我是python的新手,所以请慢慢解释。
异常No section: 5
返回No section: 5
,因为您使用的while
循环始终为true
。
您应该使用for
循环,例如:
for section in config.sections():
check = parser.get(section, "check")
hostname = parser.get(section, "hostname")
ip = parser.get(section, "IP")
port = parser.get(section, "port")
request = parser.get(section, "request")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.