python读取配置文件里面的浏览器的时候,当config.ini里面的浏览器的类型是多个的时候,读取异常。
config.ini文件:
[browserType]
browserName=Chorme
browserName=Ie #IE浏览器类型
#browserName=Firefox #火狐浏览器
[testServer]
URL=http://baidu.com
代码:
#coding=utf-8
import configparser
import os
class TestReadConfigFile(object):
def get_value(self):
root_dir=os.path.dirname(os.path.abspath('.'))
print(root_dir)
config=configparser.ConfigParser()
file_path=os.path.dirname(os.path.abspath('.'))+'/config/config.ini'
config.read(file_path,encoding='utf-8')
browser=config.get('browserType','browserName')
url=config.get('testServer','URL')
return(browser,url)
trcf=TestReadConfigFile()
print(trcf.get_value())
返回的整体报错异常:
Traceback (most recent call last):
File "D:\PythonCharmProject\Demo\test1\python读取配置文件.py", line 22, in <module>
print(trcf.get_value())
File "D:\PythonCharmProject\Demo\test1\python读取配置文件.py", line 14, in get_value
config.read(file_path,encoding='utf-8')
File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 697, in read
self._read(fp, filename)
File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 1093, in _read
raise DuplicateOptionError(sectname, optname,
configparser.DuplicateOptionError: While reading from 'D:\\PythonCharmProject\\Demo/config/config.ini' [line 5]: option 'browsername' in section 'browserType' already exists
从报错中的大概看出是File "C:\Users\ttt\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 697, in read
self._read(fp, filename),读取的异常,然后进
Configuration.py
这个里面看一下。
搜索‘DuplicateOptionError’,找到这个类,然后大概看下代码的内容,里面的注释部分如果英语不好可以百度翻译一下,起码知道个大概意思。
然后在这个类里面的函数都点进去看看,不懂就百度
def __init__(self, section, option, source=None, lineno=None):
msg = [repr(option), " in section ", repr(section),
" already exists"]
if source is not None:
message = ["While reading from ", repr(source)]
if lineno is not None:
message.append(" [line {0:2d}]".format(lineno))
message.append(": option ")
message.extend(msg)
msg = message
else:
msg.insert(0, "Option ")
Error.__init__(self, "".join(msg))
self.section = section
self.option = option
self.source = source
self.lineno = lineno
self.args = (section, option, source, lineno)
里面的东西正好可以和报错对上,section对应的config.ini里面的中括号扩起来的browserType,option对应的就是browsername