0

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.

Lance E.T. Compte
  • 932
  • 1
  • 11
  • 33
  • Maybe you need to install `my_pkg` using pip (e.g: run `pip install -e .` from inside the `my_pkg` directory). Maybe this can help you: https://stackoverflow.com/questions/1471994/what-is-setup-py – Daniser Jul 31 '20 at 18:45

1 Answers1

2

The problem is in wrong subdirectory:

If you have /some/path/my_pkg/__init__py, then the my_pkg package can be found in the /some/path directory. Your code inserts into the sys.path the /some/path/my_pkg directory instead.

VPfB
  • 14,927
  • 6
  • 41
  • 75