提问人:syrok 提问时间:10/30/2023 更新时间:10/30/2023 访问量:80
导入我自己的 python 模块时出现 ModuleNotFoundError
ModuleNotFoundError when importing my own python module
问:
所以问题是,当我尝试从我创建的模块导入某些内容时,我遇到了 ModuleNotFoundError:没有名为“<my_module>”的模块。
我的项目结构是这样的:
├── first.py
└── some_dir
├── second.py
└── third.py
您可以使用以下 3 个文件复制问题:
third.py
""" This is the third file and we store some variable here
that will be imported to the second """
a = 69
second.py
"""This is the second file. We import
a variable from the third and calculate
the sum of a and b"""
from third import a
b = 10
sum = a + b
first.py
"""This is the first and final file
where everything comes together"""
from some_dir.second import c
print(c)
当我运行 first.py 时,我收到错误:
Traceback (most recent call last):
File "/home/username/moo/goo/foo/first.py", line 3, in <module>
from some_dir.second import c
File "/home/username/moo/goo/foo/first.py", line 5, in <module>
from third import a
ModuleNotFoundError: No module named 'third'
答:
1赞
Daviid
10/30/2023
#1
您可以使用相对导入:
from .third import a
c = a + b
将 sum 更改为 c,因为这是您要导入的内容。
请记住,如果您直接执行 second.py,上述代码将不起作用,因为ImportError: attempted relative import with no known parent package
评论