I know there are many articles about this issue, but I still can not understand it clearly.
My file structure is like this:
── pkg
├── __init__.py
├── sub_pkg_A
│ ├── __init__.py
│ ├── module_in_A.py
├── sub_pkg_B
│ ├── __init__.py
│ ├── module_in_B.py
In module_in_B.py
:
from ..sub_pkg_A import module_in_A
print('Successful!')
And execute:
$ cd pkg
$ python pkg/sub_pkg_B/module_in_B.py
Traceback (most recent call last):
File "pkg/sub_pkg_B/module_in_B.py", line 1, in <module>
from ..sub_pkg_A import module_in_A
ValueError: attempted relative import beyond top-level package
$ python -m pkg.sub_pkg_B.module_in_B
Successful!
Here is my question:
- Why
python pkg/sub_pkg_B/module_in_B.py
can not work? What is the top-level package in this situation and why? - How can I fix this error when I run
python pkg/sub_pkg_B/module_in_B.py
? I know thatsys.path.append('../')
may be helpful but it doesn't work in my situation. - Why
python -m pkg.sub_pkg_B.module_in_B
can work? I knew that -m flag is to "run library module as a script" but I'm not understand it clearly. And when should I use -m flag?
Sorry for lots questions. Any suggestions and answers are helpful. Thank you!