I met an import error called no module named XX.
my project file is organized as follows:
-------A.py
|
B-----__init__.py wrote: from .C import C
|
C.py
|
D -----__init__.py wrote: from .E import E
|
E.py
In A.py, I need to import class C from C.py. but class C needs to use class E(in E.py)to run
In A.py, I wrote import B.C
In C.py, I wrote import DE
when I run the test in A.py, it gives the error: No module named 'D'
But if I test C.py, there is no problem at all.
Can anyone tell me why and how to fix it?
When you try to run A.py
, it fails because the Python interpreter (the program that runs your Python script) cannot find the D
package.
When you run C.py
, however, the interpreter does find the D
package. This is because the script you are running ( C.py
) is located in the same directory/folder as the D
package.
Detailed explanation found in the Python Docs :
When a module named
spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file namedspam.py
in a list of directories given by the variablesys.path
.sys.path
is initialized from these locations:
The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default (by convention including a site-packages directory, handled by the site module).
A quick fix would be to use a relative import in C.py
:
from .D import E
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.