I have a project that has this file structure:
f1
f2
__init__.py
a.py
b.py
main.py
main.py
from f2 import a
...
a.py
import b
...
b.py
print('Hello World!')
...
When I run main.py, I get an import error from a.py saying "ImportError: No module named 'b'" but when I run a.py, it functions as expected.
f2 was initially a github submodule and the repo name had dashes. I thought that might have been the problem so I changed f2 to a directory and copied over the files. This has not solved my issue.
I have also tried using importlib.
I would expect that a.py is able to import b.py since it is able to when I run a.py directly.
答案 0 :(得分:1)
That's because a
thinks that b
is a standalone module, so it looks for it in the PYTHONPATH
directories, including the current folder.
However, when you run from main
, b
is no longer in the current folder (main
's folder), and so a
can't find it.
To solve this, change the import in a.py
to from . import b
, which signals that b.py
is in the same package and to perform a relative import accordingly.