I am trying to run a Python file from a codebase, and have created a minimal example to explain the issue that I am facing.
foo
├── bar
│ ├── burp
│ │ └── cache.py
│ ├── __init__.py
│ └── pyro.py
└── __init__.py
The file foo/bar/pyro.py contains
def explosion():
print('boom boom')
The file foo/bar/burp/cache.py contains
from bar.pyro import explosion
def setup():
print('setting things up')
setup()
explosion()
When I execute foo/bar/burp/cache.py, I face the error as below.
$ python3 bar/burp/cache.py
Traceback (most recent call last):
File "bar/burp/cache.py", line 1, in <module>
from bar.pyro import explosion
ModuleNotFoundError: No module named 'bar'
However the program runs fine while running in the interpreter.
$ python3
Python 3.8.10 (default, Nov 7 2024, 13:10:47)
>>> exec(open('bar/burp/cache.py').read())
setting things up
boom boom
What causes this difference and how can I resolve the error in the first approach?