3

I am having trouble importing a module from within another module. I understand that that sentence can be confusing so my question and situation is exactly like the one suggested here: Python relative-import script two levels up

So lets say my directory structure is like so:

main_package
 |
 | __init__.py
 | folder_1
 |  | __init__.py
 |  | folder_2
 |  |  | __init__.py
 |  |  | script_a.py
 |  |  | script_b.py
 |
 | folder_3
 |  | __init__.py
 |  | script_c.py

And I want to access code in script_b.py as well as code from script_c.py from script_a.py.

I have also followed exactly what the answer suggested with absolute imports.

I included the following lines of code in script_a.py:

from main_package.folder_3 import script_c
from main_package.folder1.folder2 import script_b

When I run script_a.py, I get the following error:

ModuleNotFoundError: No module named 'main_package'

What am I doing wrong here?

1 Answer 1

3

This is because python doesn't know where to find main_package in script_a.py.

There are a couple of ways to expose main_package to python:

  1. run script_a.py from main_package's parent directory (say packages). Python will look for it in the current directory (packages), which contains main_package:

    python main_package/folder_1/folder_2/script_a.py
    
  2. add main_package's parent directory (packages) to your PYTHONPATH:

    export PYTHONPATH="$PYTHONPATH:/path/to/packages"; python script_a.py
    
  3. add main_package's parent directory (packages) to sys.path in script_a.py

    In your script_a.py, add the following at the top:

    import sys
    sys.path.append('/path/to/packages')
    
Sign up to request clarification or add additional context in comments.

1 Comment

The method python main_package/folder_1/folder_2/script_a.py won't add the parent directory of main_package to sys.path, so it won't work and you'll get ModuleNotFoundError. A better alternative is to use: python -m main_package.folder_1.folder_2.script_a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.