How can I list all packages/modules available to Python from within a Python script?

Tom*_*tyn 9 python package

I have looked around and do not see a solution for this. What I would like to do is get a list of all packages available in Python at run-time.

I looked at these:

But they are not what I am looking for.

I attempted to do this:

import pkgutil
for pkg in pkgutil.walk_packages():
    print(pkg)  # or do something with them...
Run Code Online (Sandbox Code Playgroud)

However, when I do this:

import sys
sys.modules.keys()???
Run Code Online (Sandbox Code Playgroud)

It appears that I have loaded all the packages which is not what I want to do, what I want is a list of strings of all packages+modules available to the current Python installation without loading them all when I do it.

spe*_*ras 8

好吧,我很好奇,我深入研究了一下pkgutil,我想出了这个,这比我预期的要简单得多:

list(pkgutil.iter_modules())
Run Code Online (Sandbox Code Playgroud)

它列出了所有作为常规文件或 zip 包可用的顶级包/模块,而不加载它们。但是,它不会看到其他类型的包,除非它们在pkgutil内部正确注册。

每个返回的条目都是一个 3 元组,其中:

  • 找到模块的文件查找器实例
  • 模块名称
  • 一个布尔值,指定它是常规模块还是包。

返回列表的示例条目:

 (FileFinder('/usr/lib/python3/dist-packages'), 'PIL', True),
Run Code Online (Sandbox Code Playgroud)

我可以确认这没有加载 PIL 包:

In [11]: sys.modules['PIL']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-b0fc0af6cc34> in <module>()
----> 1 sys.modules['PIL']

KeyError: 'PIL'
Run Code Online (Sandbox Code Playgroud)