BorchRM
BorchRM

Reputation: 33

Python import module from within module in another subpackage

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?

Upvotes: 3

Views: 1043

Answers (1)

Panwen Wang
Panwen Wang

Reputation: 3835

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')
    

Upvotes: 3

Related Questions