Colleagues!
Consider this code:
import os, sys, glob
_p = glob.glob(os.path.abspath(os.environ['MY_ROOTDIR'] +
'/opensrc/Python-*/lib/python*/site-packages/my_pkg'))
if _p and os.path.isfile(_p[0] + '/__init__.py'):
sys.path.insert(0, _p[0])
from my_pkg.all import *
else:
print("FATAL: Cannot find valid my_pkg module.")
quit()
Adding print statements shows that sys.path
is what I expect and that my_pkg's __init__.py
is found in that directory.
Nevertheless, the code leads to an error:
Traceback (most recent call last):
File "<string>", line 9, in <module>
ModuleNotFoundError: No module named 'my_pkg'
As you can see, we have a my_pkg
installed in the site-packages
of a particular Python directory. I want to load that package, no matter the Python version that is being used. There's no code in the __init__.py
that checks Python versions or anything of the sort.
Why can Python not load the module? Is there a technical reason that I cannot load a module from below the site-packages
of a different Python release? If there was some kind of code issue, I'd expect to see that choke instead of just can't find it...
.
How can I best debug this?
Thanks!
SOLVED: The solution (provided by @VPfB) is add ONLY the path down to site-packages
. Including the name of the module in the path is unnecessary. I will be careful about any OTHER modules that might come from that directory since I'm inserting at the first position in sys.path
.