我已经阅读了一些Python相对指南和绝对导入指南,并且无法找出这个ModuleNotFound
错误对我的生命。
我正在使用以下目录结构:
project
|
+-- pseudo
| |
| +-- __main__.py
| |
| +-- pseudo.py
| |
| +-- analytics_generator
| |
| +-- analytics_generator.py
| |
| +-- models
| |
| +-- blueprint.py
问题的根源在于,我正在analytics_generator.py文件中尝试从blueprint.py导入SomeClass。
在__main__.py
中执行main函数时,出现以下错误:
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1741, in <module>
main()
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File ".../project/pseudo/__main__.py", line 2, in <module>
from pseudo import Pseudo
File ".../project/pseudo/pseudo.py", line 4, in <module>
from analytics_generator.analytics_generator import AnalyticsGenerator
File ".../project/pseudo/analytics_generator/analytics_generator.py", line 1, in <module>
from models.blueprints import SomeClass
ModuleNotFoundError: No module named 'models'
我正在Pycharm中运行脚本,我的工作目录为.../project/pseudo
在analytics_generator.py文件中,如果我将导入语句更改为相对导入,则它会起作用:from .models.blueprints import SomeClass
。
但是,使用完整路径不会:
from pseudo.analytics_generator.models.blueprints import SomeClass
引发:
ModuleNotFoundError: No module named 'pseudo.analytics_generator'; 'pseudo' is not a package
非常感谢任何指导!
答案 0 :(得分:0)
不需要指定执行脚本的目录。由于您正在执行__main__.py
,因此应该执行以下操作:
from analytics_generator.models.blueprint import SomeClass
资料来源/进一步阅读:The Definitive Guide to Python import Statements: Absolute vs. Relative Import
目录结构示例
test/ # root folder packA/ # package packA subA/ # subpackage subA __init__.py sa1.py sa2.py __init__.py a1.py a2.py packB/ # package packB (implicit namespace package) b1.py b2.py math.py random.py other.py start.py
例如,假设我们正在运行
start.py
,它导入了a1
,而后者又导入了other
,a2
和sa1
。然后a1.py
中的import语句将如下所示:
绝对进口:
import other import packA.a2 import packA.subA.sa1
请注意,无需指定import test.other
或import test.packA.test.other
(其中test
是执行脚本start.py
的目录)。假设您使用的是Python 3.3及更高版本,则同样的原则应适用于您的情况regardless of __init__.py
or not。
关于后代和完整性,我将引用指南的另一部分:
[...]当Python运行脚本时,其包含的文件夹不被视为软件包。
这说明了'pseudo' is not a package
错误。