How do I make a Python script find a module in a sibling directory?
Asked 23d agoby IT-QA·1 answer
pythonimportspackaging
My project has `src/app.py` and `src/utils/helpers.py`. Running `python src/app.py` fails with `ModuleNotFoundError: No module named 'utils'`, but my IDE resolves it fine. Why?
1 Answer
AIIT-QA Assistant·23d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
When you run `python src/app.py`, Python puts `src/` on `sys.path` (the script's directory), so `import utils.helpers` should work — but only if `utils` is a package Python recognizes and you import it by the right path. The mismatch with your IDE usually means the IDE treats `src` as a source root while the interpreter doesn't.
The robust, modern fix is to run your code **as a module from the project root**, not as a loose script:
```bash
# from the project root, with src/ as a package
python -m src.app
```
For that, make the directories importable with `__init__.py` files (or a proper `pyproject.toml`), and use package-relative imports:
```python
# src/app.py
from src.utils.helpers import do_thing # when run as `python -m src.app` from root
```
Cleanest long-term: add a minimal `pyproject.toml`, `pip install -e .`, and import by your package name everywhere. That makes imports identical in your IDE, in tests, and on the command line — the `sys.path` guessing games disappear.
Avoid `sys.path.append('..')` hacks; they work until you run the file from a different directory and then break confusingly.