Skip to main content
 首页 » 编程设计

python之importError python while import exists and Pycharm recognize it

2024年12月31日7小虾米

我正在做一个项目,我遇到了一个错误,由于某种原因我无法修复。

错误是:

`from parser import WorldParser` 
`ImportError: cannot import name WorldParser` 

我正在使用 Pycharm,我尝试使用 Pycycle 来查找我是否有导入循环,但它没有找到,我还尝试手动查找循环,但我没有找到 任何。

程序结构如下:

project folder contains: 
agent.py 
graph.py 
parser.py 
simulation.py 
state.py 
utils.py 

现在我将详细说明每个文件的导入。

-----agent.py---- 
 
from utils import operation_dec,get_path_from_to 
 
-----agent.py---- 
 
-----graph.py---- 
 
none 
 
-----graph.py---- 
 
-----parser.py---- 
 
from graph import Vertex, Edge, UndirectedGraph 
 
from state import WorldState 
 
from utils import create_map_args, get_path_from_to 
 
-----parser.py---- 
 
-----simulation.py---- 
 
from parser import WorldParser 
 
from beautifultable import BeautifulTable 
 
from agent import GreedyAgent, HumanAgent, VandalAgent 
 
from state import WorldState 
 
from utils import InfoObject 
 
-----simulation.py---- 
 
-----state.py---- 
 
from beautifultable import BeautifulTable 
 
-----state.py---- 
 
-----utils.py---- 
 
from heapq import * 
 
-----utils.py---- 

感谢任何帮助,谢谢!

请您参考如下方法:

您需要更改您的导入语句

from graph import Vertex, Edge, UndirectedGraph 
from state import WorldState 
from utils import create_map_args, get_path_from_to 

以下内容:

from .graph import Vertex, Edge, UndirectedGraph 
from .state import WorldState 
from .utils import create_map_args, get_path_from_to 

当您引用同一目录中的模块时。点告诉 Python 导入来自同一目录/包中的另一个模块。如果您在 import 语句中省略圆点,Python 认为您指的是全局包而不是本地包。看看Python官方documentation以获得更详细的解释。

编辑: 我忘了提到你应该在目录中添加一个 __init__.py 文件以向 Python 指示该目录是一个 Python 包。