即使存在base.py,也没有名为“base”的模块

2024-06-17 15:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设某个目录checkerbot(您可以下载文件)。从我当前的目录中,我有一个名为checkerbot的目录,它包含4个文件,即base.pycheckers.py__init__.pymodel.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'

Tags: infrompyimport目录inputbasemodel
3条回答

您正在从checkbot目录运行脚本吗?如果您正在从父目录运行脚本,请尝试from . import basefrom checkerbot import base

目前python可能在父目录中搜索base.py

使用

from . import base

这将在checkerbot包中提供base模块的相对导入

对于model模块也有类似的情况:

from .model import model

用这个代替

from . import base

编辑

考虑下面的例子:

└── foo
    ├── __init__.py
    ├── module_bar.py
    └── module_foo.py

$ cat foo/module_bar.py 
from . import module_foo

print(module_foo.load())

$ cat foo/module_foo.py 
def load():
    print("module foo is loaded")

$ python
Python 3.8.2 (default, May  4 2020, 20:05:11) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo.module_bar
module foo is loaded

这意味着,无论何时从目录导入模块,目录中的导入都应以.开始

相关问题 更多 >