I'm comparing five methods to retrieve installed "modules", all of which I've seen in this thread
iter_modules | help("modules") | builtin_module_names | pip list | working_set | |
---|---|---|---|---|---|
Includes distributions | ❌ | ❌ | ❌ | ✔️ | ✔️ |
Includes modules (No built-in) | ✔️ | ✔️ | ❌ | ❌ | ❌ |
Includes built-in modules | ❌ | ✔️ | ✔️ | ❌ | ❌ |
Includes frozen | ✔️ | ✔️ | ❌ | ❌ | ❌ |
Includes venv | ✔️ | ✔️ | ❌ | ✔️ | ✔️ |
Includes global | ✔️ | ✔️ | ❌ | ✔️ | ✔️ |
Includes editable installs | ✔️ | ✔️ | ❌ | ✔️ | ✔️ |
Includes PyCharm helpers | ✔️ | ❌ | ❌ | ❌ | ❌ |
Lowers capital letters | ❌ | ❌ | ❌ | ❌ | ✔️ |
Time taken (665 modules total) | 53.7 msec | 1.03 sec | 577 nsec | 284 msec | 36.2 usec |
Summary
pip list
andworking_set
are for distributions, not modules.iter_modules
andhelp("modules")
are very similar, the biggest difference is thatiter_modules
doesn't include built-in.pip list
andworking_set
are very similar, only difference is thatworking_set
lowers all capital letters.- Built-in modules are only included by
help("modules")
andbuiltin_module_names
.
Related caveats
- Distributions, packages, and modules often have identical names making it easy to mistake one for the other.
importlib.util.find_spec
is for modules and is case-sensitive.sys.modules
only lists imported modules.
Distributions
I'm saying distribution instead of package because I think it will reduce misunderstandings. A distribution/package can have multiple packages/modules inside it.
An installed distribution is not always importable by the same name. For example pip install Pillow
is imported with import PIL
. Sometimes a distribution even makes multiple modules importable.
Methods (Each column in order)
iter_modules
import pkgutil{module.name for module in pkgutil.iter_modules()}
help("modules") (Only prints in terminal)
help("modules")
builtin_module_names
import sysset(sys.builtin_module_names)
pip list (Only prints in terminal)
pip list
in terminal
working_set
import pkg_resources{pkg.key for pkg in pkg_resources.working_set}
Conclusion
- For terminal I recommend
help("modules")
orpython -c "help('modules')"
. - For programmatically I recommend
iter_modules
+builtin_module_names
.- This answer in this thread
- It is however very convoluted with information, see my minimal example below.
- This answer in this thread
import sysimport pkgutildef get_installed_modules_names(): iter_modules = {module.name for module in pkgutil.iter_modules()} builtin = sys.builtin_module_names return set.union(iter_modules, builtin)