假设某个目录checkerbot(您可以下载文件)。从我当前的目录中,我有一个名为checkerbot
的目录,它包含4个文件,即base.py
、checkers.py
、__init__.py
和model.py
In [1]: import checkerbot.checkers as ck
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-d7411e2bfdb5> in <module>
----> 1 import checkerbot.checkers as ck
~/../main/checkerbot/checkers.py in <module>
----> 1 import base
2
3 class Game:
4 # Initializes the class.
5 def __init__(self):
ModuleNotFoundError: No module named 'base'
这个错误告诉我checkerbot
目录中没有base.py
,但它是错误的。我怎样才能解决这个问题?供您参考,我使用的是python 3.7.6
更新
In [2]: import .base
File "<ipython-input-2-e4256d58e84b>", line 1
import .base
^
SyntaxError: invalid syntax
假设我的当前目录是main
,而checkerbot
位于main/
。如果我运行ipython
,然后运行from . import base
,那么我得到:
In [1]: from . import base
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-a8bda1f23f19> in <module>
----> 1 from . import base
ImportError: attempted relative import with no known parent package
另一个错误:
In [5]: from checkerbot import base
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-5-3203dc774184> in <module>
----> 1 from checkerbot import base
~/../main/checkerbot/base.py in <module>
1 import tensorflow as tf
2 import numpy as np
----> 3 from model import model
4
5 agent = tf.keras.models.Sequential()
ModuleNotFoundError: No module named 'model'
您正在从checkbot目录运行脚本吗?如果您正在从父目录运行脚本,请尝试
from . import base
或from checkerbot import base
目前python可能在父目录中搜索
base.py
使用
这将在
checkerbot
包中提供base
模块的相对导入对于
model
模块也有类似的情况:用这个代替
编辑
考虑下面的例子:
这意味着,无论何时从目录导入模块,目录中的导入都应以
.
开始相关问题 更多 >
编程相关推荐