python - 将 python 2.5 移植到 3.X 时,如何替换“来自进口 *”?
问题描述
我有一个具有以下结构的 python 2.5 包:
Config.py 包含以下行:
from CommonDefines import *
在 3.7 中运行此代码会出现以下异常:
文件“../../.\ConfigLib\Config.py”,第 7 行,来自 CommonDefines 导入 * ModuleNotFoundError:没有名为“CommonDefines”的模块
将该行替换为:
from .CommonDefines import *
...在 3.7 中有效,但在 2.5 中出现以下错误:
SyntaxError: 'import *' not allowed with 'from.'
有没有办法编写这一行,以便在 2.5 和 3.X 中都可以使用?
编辑:
以下不起作用,因为第二次导入会在 2.5 中触发语法错误
try:
from CommonDefines import *
except:
from .CommonDefines import *
SyntaxError: 'import *' not allowed with 'from.'
解决方案
我只会使用正确的按名称导入,但这可以以一种骇人听闻的方式完成,供您个人使用,使用exec
:
try:
from CommonDefines import *
except ModuleNotFoundError:
exec('from .CommonDefines import *')
您甚至可以交换它们并捕获SyntaxError
.
推荐阅读
- reactjs - 如何在 React 中的动态元素列表上访问 focus()?多次使用Ref
- linux - 如果找不到文件,则将 linux `find` 和 `cp` 与输出结合起来
- product - 如何使用顶/底线和插入符号来设置 Squarespace 产品下拉/选择元素的样式?
- python - 如何在 Python 的 csv 文件中找到匹配的字符串?
- auth0 - 如何设置 Auth0“更改电子邮件脚本”设置
- python - 如何在 python 中的多行注释函数中舍入数字?
- node.js - Facebook API:无法上传视频缩略图
- powershell - 使用 Powershell 从文件名中删除前导零
- java - 在 Spring Boot 2.4 中未按正确顺序实例化 Controller Advice bean
- python - 用 Pandas 或 Pyspark 用两列表示的关系展平“树”