首页 > 解决方案 > 将 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.'

标签: pythonpython-3.xpython-2.5

解决方案


我只会使用正确的按名称导入,但这可以以一种骇人听闻的方式完成,供您个人使用,使用exec

try:
    from CommonDefines import *
except ModuleNotFoundError:
    exec('from .CommonDefines import *')

您甚至可以交换它们并捕获SyntaxError.


推荐阅读