首页 > 解决方案 > Python2 移植到 Python3:ConfigParser 异常 - MissingSectionHeaderError 上的 AttributeError

问题描述

我正在尝试将 Python2.7 脚本移植到 Python3.6+ 并且遇到了我的谷歌搜索无法解决的障碍。问题是在做了一些初始移植建议后,下面的 try: except: call 似乎不起作用。我敢肯定这很简单;只是此刻逃脱了我。

Python2.7代码:(工作)

import ConfigParser
logOutCfg = ConfigParser.ConfigParser()

try:
 if (os.path.isfile(logOutfilename)) : logOutCfg.read(logOutfilename)
except ConfigParser.MissingSectionHeaderError as e:
 pass
except ConfigParser.ParsingError as e:
 print(str(e))
 pass

Python3.6尝试的代码(在 Python 2.7 下不起作用):

from configparser import ConfigParser
logOutCfg = ConfigParser()

try:
 if (os.path.isfile(logOutfilename)) : logOutCfg.read(logOutfilename)
except ConfigParser.MissingSectionHeaderError as e:
 pass
except ConfigParser.ParsingError as e:
 print(str(e))
 pass

脚本在Python2下运行时报错为:

 File "<script>.py", line 242, in <function>
    except ConfigParser.MissingSectionHeaderError:
AttributeError: type object 'ConfigParser' has no attribute 'MissingSectionHeaderError'

我很确定我尝试了很多不同的东西。包括:except configparser.MissingSectionHeaderError但没有喜悦。

我错过了什么?在可预见的未来……至少在接下来的 9 个月内,我需要代码在 Python2 和 Python3 中工作。

标签: pythonpython-3.xpython-2.7configparser

解决方案


@mkrieger1 是对的。关键是还要 导入 configparser

import configparser
from configparser import ConfigParser

logOutCfg = ConfigParser()

try:
 if (os.path.isfile(logOutfilename)) : logOutCfg.read(logOutfilename)
except configparser.MissingSectionHeaderError as e:
 pass
except configparser.ParsingError as e:
 print(str(e))
 pass

推荐阅读