Python 模块未出现在 sys.modules 中

Python module not showing up in sys.modules

我通过解压缩 tar.gz 和 运行 setup.py.

安装了一些软件包

我正在查看

>>> import sys
>>> '[packagename]' in sys.modules

但它一直在为所有人说 False。我错过了什么?

sys.modules 仅显示已加载到您的环境中的模块。

sys.modules

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.

要获得您想要的行为,您需要先导入模块:

import sys
import packagename
'packagename' in sys.modules #True

控制台

如果您在控制台中,并想检查您是否有可用的模块,请尝试导入它。如果它不存在,你会得到一个错误:

>>> import packagename
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'packagename'

代码

如果您正在编写代码并且想要一种干净的方法来在使用之前检查模块是否存在,那就是 easier to ask for forgiveness than permission

try:
    import packagename
except ImportError:
    #handle the error

我在我的虚拟环境中执行了 conda update --all,然后在 'base' 环境中执行,错误消失了。更新我的虚拟环境后错误仍然存​​在。这就是为什么我认为它是由虚拟环境和 'base' 环境中的两个不同版本(在我的例子中是 numpy:ImportError: parent 'numpy' not in sys.modules)引起的。