我有一个项目突然停止正常运行。我不明白为什么,因为我事先没有对其进行任何更改。
构建时出现以下错误:
Traceback (most recent call last):
File ".\engine.py", line 7, in <module>
from controllers.game_panel_controller import GamePanelController
File "D:\Documents - HDD\Code\Allies_RL_Prototype\controllers\game_panel_controller.py", line 3, in <module>
import model.game as game
File "D:\Documents - HDD\Code\Allies_RL_Prototype\model\game.py", line 1, in <module>
from model.floor import Floor
File "D:\Documents - HDD\Code\Allies_RL_Prototype\model\floor.py", line 5, in <module>
from model.components.player_component import PlayerComponent
File "D:\Documents - HDD\Code\Allies_RL_Prototype\model\components\player_component.py", line 1, in <module>
import model.game as game
AttributeError: module 'model' has no attribute 'game'
这里阅读的所有内容都是导入语句,没有其他内容。
此处的文件夹结构:
.
├──engine.py
├──controllers
| └──game_panel_controller.py
└──model
├──game.py
├──floor.py
└──components
└──player_component.py
奇怪的是,有问题的陈述是
import model.game as game
当上面只有几条语句时,它就会成功运行该行。这不像是一个无效的模块或一个不存在的文件。它出什么问题了?为什么会突然停止正常运行?
这发生在 Windows 10、Python 3.5.4rc1 上,使用 Windows powershell 执行程序,如下所示:
python .\engine.py
最佳答案
我认为问题在于 game_panel_controller.py 试图在其直接路径之外导入。我认为此时 PATH 的范围包括直接目录和库目录,但不包括执行脚本的目录。
因此,即使engine.py可以导入model.game,controllers.game_panel_controller却不能(因为它不在game_panel_controller脚本的直接目录中)。
你可以做到
from .. import model.game
或者您也可以使用符号链接(symbolic link)或代码重构(或者您可以在导入之前考虑修改路径)。
关于Python 模块在导入语句中存在属性错误,即使导入语句在之前的代码中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53808856/