python - 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 中工作。
解决方案
@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
推荐阅读
- python - 仅在行尾删除连字符正则表达式 python r
- python - 即使安装了 selenium,导入 selenium 时也会出错
- google-apps-script - 在脚本中使用 Google 表格 RIGHT 公式
- unit-testing - 笑话:模拟高阶函数
- java - 无法访问计算引擎外部的 Java 应用程序,但它在 localhost 上运行
- mysql - MariaDB:如何对来自 GROUPED 父级的子值求和
- arrays - 酶单元测试组件
- spring-boot - SpringBoot 应用退出时间
- sql-server - 处理 SQL Server 表中的缺失列
- ios - Apple 登录无法在 iOS 14 设备和模拟器上运行