pythonpython-3.xpython-importpython-module

ModuleNotFoundError when import package from src folder


What is wrong with this python structure? I have read multiple docs and forums on this issue i just can't seem to get it solved.

.
└── src
    ├── __init__.py
    ├── lib
    │   ├── hello.py
    │   └── __init__.py
    ├── libtwo
    │   ├── __init__.py
    │   └── world.py
    └── main.py

world.py

def helloworld():
    print("Hello World!")

hello.py

from libtwo.world import helloworld

helloworld()

main.py

from libtwo.world import helloworld

helloworld()

(it runs fine from main.py)

  File "src/lib/hello.py", line 1, in <module>
    from libtwo.world import helloworld
ModuleNotFoundError: No module named 'libtwo'

the following gives

  File "lib/hello.py", line 1, in <module>
    from ..libtwo.world import helloworld
ImportError: attempted relative import with no known parent package
from ..libtwo.world import helloworld

helloworld()

using vscode i tried to set up workspaces and configs, all the lot. "python.terminal.executeInFileDir": true

(yes i am using a virtual env)

virtualenv sys path entries.

according to some sources if i don't see my directory in the virtualenv that means something is wrong

(my_venv) ➜  src python main.py 
>>> import sys
>>> sys.path
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/user/Documents/py/myui/subject_a/my_venv/lib/python3.8/site-packages']
>>> 

running sys.path from main.py

(my_venv) ➜  src python main.py 
['/home/user/Documents/py/myui/subject_a/src', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/user/Documents/py/myui/subject_a/my_venv/lib/python3.8/site-packages']

I really can't pin point what is wrong with my structure, i have been doing this for years and today nothing seems to work.


Solution

  • In your hello.py file, you import the module using libtwo.world. This means Python should look for modules from src directory.

    When you run main.py, it works fine because Python looks for modules in the working directory which is src.

    You can set PYTHONPATH to explicitly specify the search path for module files. Refer to https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH.

    export PYTHONPATH=$(pwd)/src
    python src/lib/hello.py