Search code examples
pythonimportpycharmpython-venv

Python import modules solution for scripts


My project structure looks like

--src/core

--src/bin

i have a bunch of scripts that i want to run from bin that import from src/core

when i run them from PyCharms everything works fine.

when i run the same script from my terminal, i get ModuleNotFound error

the difference is in the PYTHONPATH (Pycharm adds the root directory at runtime - venv does not)

my current hack is to add this to all my scripts that i want to call

import sys, os
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

what is a more elegant solution to this?


Solution

  • You could make your project a package, run it with a runner script or with python -m my_app, and have access to relative imports (from . import foo), as well as package-based ones (from my_app import foo)