Search code examples
pythonmodulepackagepython-importimporterror

ModuleNotFoundError on different OS with same setup for local package


Essentially, the main issue is that a package is not being seen for importing on Ubuntu where it is for Git Bash on Windows.

Here is the relevant directory structure with the library folder being the problematic package/module.

project-dir/
    services/
        task.py
    library/
        __init__.py
        module.py

In the task.py file, I have imports that take the following syntax:

from library.module import function

In the project-dir folder, I run the following command: python services/task.py.

On Git Bash on Windows, this works perfectly. However, on Ubuntu, I get a ModuleNotFoundError thrown. Below is the abstracted aforementioned error:

Traceback (most recent call last):
  File "services/task.py", line 3, in <module>
    from library.module function
ModuleNotFoundError: No module named 'library'

Note: I saw this question, which looks very similar to my question, but adding things to PYTHONPATH did not fix things. Here is the output for PYTHONPATH for me:

/home/username/.local/lib/python3.6/site-packages:/usr/lib/python3.6:/usr/lib/python3.6/lib-dynload:/usr/local/lib/python3.6/dist-packages:/usr/lib/python3/dist-packages

Solution

  • Since no one posted an answer, and @forty_two happened to give me insight into what I need to do, I will explain my implementation of his suggestion.

    I created a file called add_project_path.py in the services directory. The scripts contents is as follows:

    import sys
    import os
    
    # Adds the project path
    sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
    

    This gets the add_project_path.py's path, gets the directory in which it resides, and gets that directory's parent directory, which is the project folder. Then, the project folder is added to the path, which solves the issue.

    Edit:

    Also, to explain further, I added import add_project_path at the top of my imports for task.py, which allowed the add_project_path module to import the project path before any of the other imports occur.