I created a module named myutils. This is the file structure I use:
./mypackages
./mypackages/myutils
./mypackages/myutils/util1.py
./mypackages/myutils/util2.py
./myexecs
./myexecs/user_executable1.py
I correctly set PYTHONPATH=./
in ./myexecs/user_executable1.py I can easily use the utils:
from my_packages import myutils
myutils.util1.func1()
In util1.py I can use util2.py:
from . import util2
util2.func2()
The problem arises when I wish to use util1.py directly as a main entrypoint. It has a
if __name__ == "__main__": main()
entry point, but if I just execute it directly, it fails to import util2 (from . import util1 fails).
It does succeed if I execute it using python -m mypackages.myutils.util1
Any idea how can I make util1 import its' sibilings using from . import ... and yet being able to execute it directly from the cmd without executing it as a module?
1 Answer 1
Just use abolute import everywhere in your code (from . import util2 will be from mypackages.myutils import util2) and run your exec with python -m myexecs.user_executable1 and you will be good
2 Comments
python -m is the more logical. When you make a script /tmp/foo.py you need to import your package, sometimes from another folder, but that's pure Python - the only thing to fix is "how to import this module in a clean way" (I would say: setup.py + venv + pip install). For me you are trying to fix something on the wrong level, this should not be fixed in your code, but in your setup. (well i think..)Explore related questions
See similar questions with these tags.