How to list all installed packages and their versions in Python?

Question:

Is there a way in Python to list all installed packages and their versions?

I know I can go inside python/Lib/site-packages and see what files and directories exist, but I find this very awkward. What I’m looking for something that is similar to npm list i.e. npm-ls.

Asked By: jsalonen

||

Answers:

help('modules') should do it for you.

in IPython :

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath
Answered By: Ashwini Chaudhary

If you have pip install and you want to see what packages have been installed with your installer tools you can simply call this:

pip freeze

It will also include version numbers for the installed packages.

Update

pip has been updated to also produce the same output as pip freeze by calling:

pip list

Note

The output from pip list is formatted differently, so if you have some shell script that parses the output (maybe to grab the version number) of freeze and want to change your script to call list, you’ll need to change your parsing code.

Answered By: Jeff LaFay

yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )

with pip installed packages, you can do a

pip freeze

and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do

mkvirtualenv my_new_project

and then (inside that virtualenv), do

pip install all_your_stuff

This way, you can workon my_new_project and then pip freeze to see which packages are installed for that virtualenv/project.

for example:

➜  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)➜  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)➜  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)➜  ~  

or if you have a python package with a requirements.pip file,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

will do the trick

Answered By: Andbdrew

Here’s a way to do it using PYTHONPATH instead of the absolute path of your python libs dir:

for d in `echo "${PYTHONPATH}" | tr ':' 'n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' 'n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....
Answered By: chown

For easy_install (deprecated, Python <= v2.7, do not use this, use pip instead; use this only in old projects that still use easy_install)

You can try : Yolk

For install yolk, try:

easy_install yolk

Yolk is a Python tool for obtaining information about installed Python
packages and querying packages avilable on PyPI (Python Package
Index).

You can see which packages are active, non-active or in development
mode and show you which have newer versions available by querying
PyPI.

Answered By: llazzaro

If you want to get information about your installed python distributions and don’t want to use your cmd console or terminal for it, but rather through python code, you can use the following code (tested with python 3.4):

import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_only=True):
    print(i)

The pip.get_installed_distributions(local_only=True) function-call returns an iterable and because of the for-loop and the print function the elements contained in the iterable are printed out separated by new line characters (n).
The result will (depending on your installed distributions) look something like this:

cycler 0.9.0
decorator 4.0.4
ipykernel 4.1.0
ipython 4.0.0
ipython-genutils 0.1.0
ipywidgets 4.0.3
Jinja2 2.8
jsonschema 2.5.1
jupyter 1.0.0
jupyter-client 4.1.1
#... and so on...
Answered By: frosty

from command line

python -c help('modules')

can be used to view all modules, and for specific modules

python -c help('os')

For Linux below will work

python -c "help('os')"
Answered By: Npradhan

If you’re using anaconda:

conda list

will do it! See: https://conda.io/docs/_downloads/conda-cheatsheet.pdf

Answered By: A. Bollans

To run this in later versions of pip (tested on pip==10.0.1) use the following:

from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
    print(requirement)
Answered By: exhuma

My take:

#!/usr/bin/env python3

import pkg_resources

dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
for i in dists:
    print(i)
Answered By: alfredocambera

If this is needed to run from within python you can just invoke subprocess

from subprocess import PIPE, Popen

pip_process = Popen(["pip freeze"], stdout=PIPE,
                   stderr=PIPE, shell=True)
stdout, stderr = pip_process.communicate()
print(stdout.decode("utf-8"))
Answered By: juftin

for using code, for example to check what modules in Hackerrank etc :

import os
os.system("pip list")
Answered By: Chrono Hax

For Windows 10, I think this is what you are looking for a list of available installed Pythons. This is different from a list of packages as you can see below. Also, on Ubuntu 20.04, I think the command is Python3 -0 list.
Yes, this works similar to node version manager.

c:UsersuserAppDataLocalProgramsPython>py -0 list

Python 0 not found!

Installed Pythons found by py Launcher for Windows

 -3.10-64 *
 -3.9-64
 -3.7-64
 -3.6-64
 -2.7-64

Requested Python version (0) not installed, use -0 for available pythons

c:UsersuserAppDataLocalProgramsPython>py -0p
Installed Pythons found by py Launcher for Windows

 -3.10-64       C:Python310python.exe *

 -3.9-64        C:UsersuserAppDataLocalProgramsPythonPython39python.exe

 -3.7-64        C:Program Files (x86)Microsoft Visual StudioSharedPython37_64python.exe

 -3.6-64        C:Program Files (x86)Microsoft Visual StudioSharedPython36_64python.exe

 -2.7-64        C:Python27amd64python.exe

See: https://www.infoworld.com/article/3617292/how-to-use-pythons-py-launcher-for-windows.html

See Also: https://www.freecodecamp.org/news/manage-multiple-python-versions-and-virtual-environments-venv-pyenv-pyvenv-a29fb00c296f/

From the above link, "If you wish to use multiple versions of Python on a single machine, then pyenv is a commonly used tool to install and switch between versions. This is not to be confused with the previously mentioned depreciated pyvenv script. It does not come bundled with Python and must be installed separately." — Note: This acts similar to Node Version Manager with versions of Node.js and NPM.

See Also: https://github.com/pyenv-win/pyenv-win#installation

Action: Open PowerShell and type the following web request. The link above offers other approaches as well, but this appears to be the easiest approach. The name of the runtime output file is not a name variant like ‘pyenv-win’ but actually ‘pyenv’, as originally expected.

PS C:Usersuser> Invoke-WebRequest -UseBasicParsing -Uri "https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1" -OutFile "./install-pyenv-win.ps1"; &"./install-pyenv-win.ps1"

pyenv-win 2.64.11 installed.
No updates available.
PS C:Usersuser>

Example Output for working with ‘pyenv’, Python’s Version Manager.

C:Usersuser>pyenv --version
pyenv 2.64.11

C:Usersname>pyenv
pyenv 2.64.11
Usage: pyenv <command> [<args>]

Some useful pyenv commands are:
   commands     List all available pyenv commands
   duplicate    Creates a duplicate python environment
   local        Set or show the local application-specific Python version
   global       Set or show the global Python version
   shell        Set or show the shell-specific Python version
   install      Install a Python version using python-build
   uninstall    Uninstall a specific Python version
   update       Update the cached version DB
   rehash       Rehash pyenv shims (run this after installing executables)
   vname        Show the current Python version
   version      Show the current Python version and its origin
   version-name Show the current Python version
   versions     List all Python versions available to pyenv
   exec         Runs an executable by first preparing PATH so that the selected Python
   which        Display the full path to an executable
   whence       List all Python versions that contain the given executable

See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/pyenv-win/pyenv-win#readme

C:Usersname>pyenv commands
--version
commands
duplicate
exec
export
global
help
install
local
rehash
shell
shims
uninstall
update
version-name
version
versions
vname
whence
which

C:Usersname>pyenv version
No global python version has been set yet. Please set the global version by typing:
pyenv global 3.7.2

C:Usersuser>pyenv local
no local version configured for this directory

C:Usersuser>pyenv global
no global version configured

C:Usersuser>pyenv local 3.9-64
pyenv specific python requisite didn't meet. Project is using different version of python.
Install python '3.9-64' by typing: 'pyenv install 3.9-64'

My Note: Version name from ‘https://www.python.org/downloads/’ is different to those provided by ‘pyenv’. This version was already installed locally, but it is outside the control of this Python version manager, so it is not visible to the manager.

C:Usersuser>pyenv install 3.8.10-64
:: [Info] ::  Mirror: https://www.python.org/ftp/python
pyenv-install: definition not found: local

My Note(s): This Python version is not part of the managed list although this version exists at ‘https://www.python.org/downloads/’. So you must see the list provided by the manager. See all available versions with `pyenv install –list’.

C:Usersuser>pyenv install --list
Note: Review the list from this call and make your selection.

C:Usersuser>pyenv install 3.8.10
:: [Info] ::  Mirror: https://www.python.org/ftp/python
:: [Downloading] ::  3.8.10 ...
:: [Downloading] ::  From https://www.python.org/ftp/python/3.8.10/python-3.8.10-amd64-webinstall.exe
:: [Downloading] ::  To   C:Usersuser.pyenvpyenv-wininstall_cachepython-3.8.10-amd64-webinstall.exe
:: [Installing] ::  3.8.10 ...
:: [Info] :: completed! 3.8.10

My Note(s): With this Python version manager, ‘pyenv’, following installation, it appears that one must designate the version as ‘local’ or ‘global’ after the installation which would follow the same paradigm as the Node.js Version Manager (NVM). Again, from what I can see, the Python version manager can only see what versions of Python the manager installs; and it can only uninstall a version it has installed with the Python version manager.

C:Usersuser>pyenv local 3.8.10

C:Usersuser>pyenv local
3.8.10

C:Usersuser>pyenv version
3.8.10 (set by C:Usersuser.python-version)

C:Usersuser>pyenv versions
* 3.8.10 (set by C:Usersuser.python-version)

C:Usersuser>pyenv vname
3.8.10

C:Usersuser>pyenv global
no global version configured

The following below is for working with packages.

See Also: https://www.freecodecamp.org/news/manage-multiple-python-versions-and-virtual-environments-venv-pyenv-pyvenv-a29fb00c296f/

From the above link, "When the environment is active, any packages can be installed to it via pip as normal. By default, the newly created environment will not include any packages already installed on the machine. As pip itself will not necessarily be installed on the machine. It is recommended to first upgrade pip to the latest version, using ‘pip install –upgrade pip’." — I performed the pip upgrade just before making these two calls to list the packages and their versions below.

c:UsersuserAppDataLocalProgramsPython>pip list

Package    Version
---------- -------
pip        22.1
setuptools 62.2.0
wheel      0.37.1

c:UsersuserAppDataLocalProgramsPython>pip list --local

Package    Version
---------- -------
pip        22.1
setuptools 62.2.0
wheel      0.37.1

According to the pkg_resources documentation, the recommended way now is to use importlib.metadata, which is part of the standard library since version 3.8.

from importlib import metadata
for dist in metadata.distributions():
    print(f"{dist.name}=={dist.version}")
Answered By: Seppo Enarvi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.