Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - ModuleNotFoundError: No module named

I'm new in Python and I'm having the following error with this simple example:

This is my project structure:

python_project
.
├── lib
│   ├── __init__.py
│   └── my_custom_lib.py
└── src
    ├── __init__.py
    └── main.py

And this is the error when I execute the src/main.py file:

☁  python_project  python src/main.py

Traceback (most recent call last):
  File "src/main.py", line 3, in <module>
    from lib import my_custom_lib
ImportError: No module named lib

If I move the main.py file to the root and then I execute this file again, works... but is not working inside src/ directory

This is my main.py:

from lib import my_custom_lib

def do_something(message):
        my_custom_lib.show(message)

do_something('Hello World!')

Note: When I execute the same code from Pycharm is working fine, but not from my terminal.

like image 678
Nicolas Avatar asked Apr 30 '20 20:04

Nicolas


People also ask

How do you fix ModuleNotFoundError No module named Sklearn?

The Python "ModuleNotFoundError: No module named 'sklearn'" occurs when we forget to install the scikit-learn module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install scikit-learn command.

Why can't Python find my module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

Can not import name Python?

This error generally occurs when a class cannot be imported due to one of the following reasons: The imported class is in a circular dependency. The imported class is unavailable or was not created. The imported class name is misspelled.


1 Answers

Your PYTHONPATH is set to the current directory from the program you execute. So if you're executing something inside a directory src, it will never be able to find the directory lib because it's outside the path. There's a few choices;

  • Just move lib/ into src/ if it belongs to your code. If it's an external package, it should be pip installed as Henrique Branco mentioned.
  • Have a top-level script outside of src/ that imports and runs src.main. This will add the top-level directory to python path.
  • In src/main.py modify sys.path to include the top-level directory. This is usually frowned upon.
  • Invoke src/main.py as a module with python -m src.main which will add the top-level directory to the python path. Kind of annoying to type, plus you'll need to change all your imports.
like image 117
MarkM Avatar answered Sep 27 '22 18:09

MarkM