Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

Python relative imports from parent directory

Here is the file structure I have :

app/
    main.py
    folder/
        a.py
        b.py

In the file a.py i have import b, and in main.py, i have import folder.a.

When I run python3 a.py from folder/, everything works fine. However when I run python3 main.py from app/, I get ModuleNotFoundError: No module named b, which is caused by the import in a.py

I have found a way to avoid this, which is to simply put import folder.b in a.py, but this is not very satisfying, as I can no longer lauch a.py from folder/.

What should i do for the import to work from both folder ? Please don't answer my question by saying i should modify my architecture, i've been looking for answers to this question on SO for 2 hours but i haven't found anything convincing.

question from:https://stackoverflow.com/questions/65944509/python-relative-imports-from-parent-directory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In a.py try:

from folder import b

or:

from folder.anotherfolder import b

or in main.py:

from folder import a, b

or:

from folder.anotherfolder import a, b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...