Python2移植到Python3:ConfigParser异常-MissingSectionHeaderError上的AttributeError

问题描述 投票:0回答:2

我正在尝试将Python2.7脚本移植到Python3.6 +,并且遇到了我的Google搜索无法解决的障碍。问题是尝试:例外:在做一些初步的移植建议后,下面的呼叫似乎不起作用。我相信这很简单;现在就逃脱了。

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但没有喜悦。

我想念的是什么?在可预见的将来,我需要代码在Python2和Python3中都可以使用……至少在接下来的9个月内。

python python-3.x python-2.7 configparser
2个回答
1
投票

@@ mkrieger1没问题。关键还在于导入配置分析器

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

0
投票

您的Python 3.6代码基本上是正确的。唯一的问题是您试图从ConfigParser类而不是configparser模块中获取异常。这里最主要的困惑很可能来自这样一个事实,即模块名称在Python 3中更改为与PEP8 standards更加内联。最初,ConfigParser模块和类共享相同的名称,但是在Python 3中并非如此。

以下代码应在Python 2和3中工作。

try:
    import configparser
except ImportError: 
    import ConfigParser as 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(e)

这里是正在发生的事情的快速细分。

try:
    import configparser
except ImportError: 
    import ConfigParser as configparser

尝试导入Python 3 configparser模块。如果在Python 2中,这将引发ImportError。我们抓住了它,而是导入了ConfigParser并用configparser为其别名。

logOutCfg = configparser.ConfigParser()

从上面导入的ConfigParser模块中获取configparser类,并将其实例化。

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

尝试像以前一样打开文件,但不要尝试从ConfigParser类获取异常,而要从configparser模块获取它们。

© www.soinside.com 2019 - 2024. All rights reserved.