LuCima LuCima - 1 year ago 107
Python Question

Python import error, cannot find module

My project structure is like this:

dir A/
main.py
__init__.py
modules/
a.py
__init__.py
components/
b.py
c.py
__init__.py


In
main.py
, I've written
from modules.a import xxx
. In
a.py
, I want to import module
b.py
and in
b.py
, I want to import
c.py
.

Here's the problem, I wrote
from components.b import xxx
in
a.py
, I got import error when I ran
main.py
. I got the same error if I write
from c import xxx
in
b.py
. But if I ran
b.py
directly, it went well. I've tried many times and found that I have to write all import sentences considering
dir A
as the root directory. For example, if I write
from modules.components.b import xxx
in
a.py
and
from modules.components.c import xxx
in
b.py
, the program goes well.

Someone says that change environment path can solve this problem. But don't I have to set the path again and again once I change the position of the whole project?

Is there any decent solution? I'm very glad to hear someone's help.

Answer Source

Relative imports.

from .components.b import xxx
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download