简体   繁体   English

Python3 无法在 sys.path 中加载模块

[英]Python3 Cannot Load Module Within sys.path

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.添加打印语句表明sys.path是我所期望的,并且 my_pkg 的__init__.py位于该目录中。

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.如您所见,我们在特定my_pkg目录的site-packages中安装了一个 my_pkg。 I want to load that package, no matter the Python version that is being used.无论正在使用的 Python 版本如何,我都想加载 package。 There's no code in the __init__.py that checks Python versions or anything of the sort. __init__.py中没有代码可以检查 Python 版本或类似的任何内容。

Why can Python not load the module?为什么Python不能加载模块? Is there a technical reason that I cannot load a module from below the site-packages of a different Python release?是否有技术原因导致我无法从不同 Python 版本的site-packages下方加载模块? If there was some kind of code issue, I'd expect to see that choke instead of just can't find it... .如果有某种代码问题,我希望看到那个扼流圈而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 .已解决:解决方案(由@VPfB 提供)仅添加到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 .我会小心可能来自该目录的任何其他模块,因为我在sys.path的第一个 position 处插入。

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.如果你有/some/path/my_pkg/__init__py ,那么my_pkg package 可以在/some/path目录中找到。 Your code inserts into the sys.path the /some/path/my_pkg directory instead.您的代码改为将/some/path/my_pkg目录插入到sys.path中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM