0

I am new in python programming and I encounter some problem when I use import statement.
The following is my directory.

package/
    __init__.py
    main.py
    subpackage_a/
        __init__.py
        a.py
        subpackage_b/
            __init__.py
            b.py
       

In package/main.py I use import package.subpackage_a.a to import a.py.
In package/subpackage_a/a.py I try to add package/subpackage_a/subpackage_b to PYTHONPATH by modifying sys.path in a.py and use import b to import b.py.
However, when I run package/main.py, the ModuleNotFoundError appear. Although changing PYTHONPATH arbitrarily is not a good habit, I still want to know why I can't successfully import package/subpackage_a/subpackage_b/b.py by modifying sys.path in package/subpackage_a/a.py when I run package/main.py.
Thanks a lot.

JoeWu
  • 1
  • Have you tried executing the script using `python -m package.main` – Imanpal Singh Aug 16 '20 at 05:59
  • As it appears, it depends on where you calling it from. You should avoid hacking `sys.path`. If you call main.py outside package `python package/main.py` your imports should work as the base directory will include package as a module. If you wish to call them inside package, where main.py is then remove `package.` from your imports – Prayson W. Daniel Aug 16 '20 at 06:05

1 Answers1

-1

Your question may have been answered here

to properly add to PYTHONPATH you need to use the absolute path like so:

import sys
sys.path.append('/path/to/module/')
Ahmadore
  • 23
  • 1
  • 6