0

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?

2 Answers 2

1

To solve this you can run your Python script with the PYTHONPATH set to the foo directory, allowing Python to find bar.pyro from within foo:

$ PYTHONPATH=foo python3 bar/burp/cache.py

This tells Python to treat the foo directory as part of the module search path.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use relative imports. In your cache.py file:

from ..pyro import explosion
def setup():
    print('setting things up')

setup()
explosion()

and run your Python script as a module, starting from the first folder outside your top level directory, using:

python -m foo.bar.burp.cache

Comments

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.