I would like to get a list of Python modules, which are in my Python installation (UNIX server).
How can you get a list of Python modules installed in your computer?
Warning: Adam Matan discourages this use in pip > 10.0. Also, read @sinoroc's comment below
This was inspired by Adam Matan's answer (the accepted one):
import tabulate
try:
from pip import get_installed_distributions
except:
from pip._internal.utils.misc import get_installed_distributions
tabpackages = []
for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]):
tabpackages.append([package.location, package.key, package.version])
print(tabulate.tabulate(tabpackages))
which then prints out a table in the form of
19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py
------------------------------------------- -------------- ------
/home/pi/.local/lib/python2.7/site-packages enum-compat 0.0.2
/home/pi/.local/lib/python2.7/site-packages enum34 1.1.6
/home/pi/.local/lib/python2.7/site-packages pexpect 4.2.1
/home/pi/.local/lib/python2.7/site-packages ptyprocess 0.5.2
/home/pi/.local/lib/python2.7/site-packages pygatt 3.2.0
/home/pi/.local/lib/python2.7/site-packages pyserial 3.4
/usr/local/lib/python2.7/dist-packages bluepy 1.1.1
/usr/local/lib/python2.7/dist-packages click 6.7
/usr/local/lib/python2.7/dist-packages click-datetime 0.2
/usr/local/lib/python2.7/dist-packages construct 2.8.21
/usr/local/lib/python2.7/dist-packages pyaudio 0.2.11
/usr/local/lib/python2.7/dist-packages tabulate 0.8.2
------------------------------------------- -------------- ------
which lets you then easily discern which packages you installed with and without sudo
.
A note aside: I've noticed that when I install a packet once via sudo
and once without, one takes precedence so that the other one isn't being listed (only one location is shown). I believe that only the one in the local directory is then listed. This could be improved.
In case you have an anaconda python distribution installed, you could also use
$conda list
in addition to solutions described above.
pip freeze does it all finding packages however one can simply write the following command to list all paths where python packages are.
>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
There are many ideas, initially I am pondering on these two:
pip
cons: not always installed
help('modules')
cons: output to console; with broken modules (see ubuntu...) can segfault
I need an easy approach, using basic libraries and compatible with old python 2.x
And I see the light: listmodules.py
Hidden in the documentation source directory in 2.5 is a small script that lists all available modules for a Python installation.
Pros:
uses only imp, sys, os, re, time
designed to run on Python 1.5.2 and newer
the source code is really compact, so you can easy tinkering with it, for example to pass an exception list of buggy modules (don't try to import them)
Run the following in your python editor or IPython:
import pkg_resources
installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}
print(installed_packages)
Read other answers and pulled together this combo, which is quickest and easiest inside Python.
Conveniently you can then get items from your dict easily, i.e.
installed_packages['pandas']
>> '1.16.4'
This solution is primary based on modules importlib
and pkgutil
and work with CPython 3.4 and CPython 3.5, but has no support for the CPython 2.
Explanation
sys.builtin_module_names
- names all built-in modules (look my answer here)pkgutil.iter_modules()
- returns an information about all available modulesimportlib.util.find_spec()
- returns an information about importing module, if existsBuiltinImporter
- an importer for built-in modules (docs)SourceFileLoader
- an importer for a standard Python module (by default has extension *.py) (docs)ExtensionFileLoader
- an importer for modules as shared library (written on the C or C++)Full code
import sys
import os
import shutil
import pkgutil
import importlib
import collections
if sys.version_info.major == 2:
raise NotImplementedError('CPython 2 is not supported yet')
def main():
# name this file (module)
this_module_name = os.path.basename(__file__).rsplit('.')[0]
# dict for loaders with their modules
loaders = collections.OrderedDict()
# names`s of build-in modules
for module_name in sys.builtin_module_names:
# find an information about a module by name
module = importlib.util.find_spec(module_name)
# add a key about a loader in the dict, if not exists yet
if module.loader not in loaders:
loaders[module.loader] = []
# add a name and a location about imported module in the dict
loaders[module.loader].append((module.name, module.origin))
# all available non-build-in modules
for module_name in pkgutil.iter_modules():
# ignore this module
if this_module_name == module_name[1]:
continue
# find an information about a module by name
module = importlib.util.find_spec(module_name[1])
# add a key about a loader in the dict, if not exists yet
loader = type(module.loader)
if loader not in loaders:
loaders[loader] = []
# add a name and a location about imported module in the dict
loaders[loader].append((module.name, module.origin))
# pretty print
line = '-' * shutil.get_terminal_size().columns
for loader, modules in loaders.items():
print('{0}\n{1}: {2}\n{0}'.format(line, len(modules), loader))
for module in modules:
print('{0:30} | {1}'.format(module[0], module[1]))
if __name__ == '__main__':
main()
Usage
For the CPython3.5 (truncated)
$ python3.5 python_modules_info.py
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
30: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast | built-in
_codecs | built-in
_collections | built-in
_functools | built-in
_imp | None
_io | built-in
_locale | built-in
_operator | built-in
_signal | built-in
_sre | built-in
_stat | built-in
_string | built-in
_symtable | built-in
_thread | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
227: <class '_frozen_importlib_external.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__ | /usr/local/lib/python3.5/__future__.py
_bootlocale | /usr/local/lib/python3.5/_bootlocale.py
_collections_abc | /usr/local/lib/python3.5/_collections_abc.py
_compat_pickle | /usr/local/lib/python3.5/_compat_pickle.py
_compression | /usr/local/lib/python3.5/_compression.py
_dummy_thread | /usr/local/lib/python3.5/_dummy_thread.py
_markupbase | /usr/local/lib/python3.5/_markupbase.py
_osx_support | /usr/local/lib/python3.5/_osx_support.py
_pydecimal | /usr/local/lib/python3.5/_pydecimal.py
_pyio | /usr/local/lib/python3.5/_pyio.py
_sitebuiltins | /usr/local/lib/python3.5/_sitebuiltins.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
64: <class '_frozen_importlib_external.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bisect | /usr/local/lib/python3.5/lib-dynload/_bisect.cpython-35m-x86_64-linux-gnu.so
_bz2 | /usr/local/lib/python3.5/lib-dynload/_bz2.cpython-35m-x86_64-linux-gnu.so
_codecs_cn | /usr/local/lib/python3.5/lib-dynload/_codecs_cn.cpython-35m-x86_64-linux-gnu.so
_codecs_hk | /usr/local/lib/python3.5/lib-dynload/_codecs_hk.cpython-35m-x86_64-linux-gnu.so
_codecs_iso2022 | /usr/local/lib/python3.5/lib-dynload/_codecs_iso2022.cpython-35m-x86_64-linux-gnu.so
(****************************truncated*******************************)
For the CPython3.4 (truncated)
$ python3.4 python_modules_info.py
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
54: <class '_frozen_importlib.BuiltinImporter'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_ast | built-in
_bisect | built-in
_codecs | built-in
_collections | built-in
_datetime | built-in
_elementtree | built-in
_functools | built-in
_heapq | built-in
_imp | None
_io | built-in
_locale | built-in
_md5 | built-in
_operator | built-in
_pickle | built-in
_posixsubprocess | built-in
_random | built-in
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
246: <class '_frozen_importlib.SourceFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
__future__ | /usr/lib/python3.4/__future__.py
_bootlocale | /usr/lib/python3.4/_bootlocale.py
_collections_abc | /usr/lib/python3.4/_collections_abc.py
_compat_pickle | /usr/lib/python3.4/_compat_pickle.py
_dummy_thread | /usr/lib/python3.4/_dummy_thread.py
_markupbase | /usr/lib/python3.4/_markupbase.py
_osx_support | /usr/lib/python3.4/_osx_support.py
_pyio | /usr/lib/python3.4/_pyio.py
(****************************truncated*******************************)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
44: <class '_frozen_importlib.ExtensionFileLoader'>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_bz2 | /usr/lib/python3.4/lib-dynload/_bz2.cpython-34m-x86_64-linux-gnu.so
_codecs_cn | /usr/lib/python3.4/lib-dynload/_codecs_cn.cpython-34m-x86_64-linux-gnu.so
_codecs_hk | /usr/lib/python3.4/lib-dynload/_codecs_hk.cpython-34m-x86_64-linux-gnu.so
_codecs_iso2022 | /usr/lib/python3.4/lib-dynload/_codecs_iso2022.cpython-34m-x86_64-linux-gnu.so
_codecs_jp | /usr/lib/python3.4/lib-dynload/_codecs_jp.cpython-34m-x86_64-linux-gnu.so
_codecs_kr | /usr/lib/python3.4/lib-dynload/_codecs_kr.cpython-34m-x86_64-linux-gnu.so
_codecs_tw | /usr/lib/python3.4/lib-dynload/_codecs_tw.cpython-34m-x86_64-linux-gnu.so
_crypt | /usr/lib/python3.4/lib-dynload/_crypt.cpython-34m-x86_64-linux-gnu.so
(****************************truncated*******************************)