Import a Python file from different directory in Terminal and Jupyter

44 Views Asked by At

I have a package structured like this and contained within a folder.

project
├── jupyter.ipynb
└── package
    ├── __init__.py (from . import app1, app2)
    ├── app1
    │   ├── __init__.py (from . import foo)
    │   └── foo.py
    └── app2
        ├── __init__.py (from . import bar)
        └── bar.py

What I want to do is import bar.py into foo.py, and for this I add the following in foo.py:

from ..app2 import bar

Now, from the jupyter.ipynb file the libraries are successfully imported as follows:

import sys
sys.path.insert(1, './')
from package import app1, app2

However, in the terminal, inside the project folder, the following command throws the error ImportError: attempted relative import with no known parent package.

cd project
python package/app1/foo.py

What am I missing? I have also tried absolute imports (e.g., from package.app2.bar import func() or from app2.bar import func()) but they don't work. I have also checked this and this posts.

Thanks in advance!

0

There are 0 best solutions below