How to check version of Python modules

How to check version of Python modules

I suggest using pip in place of easy_install. With pip, you can list all installed packages and their versions with

pip freeze

In most linux systems, you can pipe this to grep(or findstr on Windows) to find the row for the particular package youre interested in:

$ pip freeze | grep lxml

c:> pip freeze | findstr lxml

For an individual module, you can try the __version__ attribute, however there are modules without it:

$ python -c import requests; print(requests.__version__)
$ python -c import lxml; print(lxml.__version__)
Traceback (most recent call last):
  File <string>, line 1, in <module>
AttributeError: module object has no attribute __version__

Lastly, as the commands in your question are prefixed with sudo, it appears youre installing to the global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper

You can try

>>> import statlib
>>> print statlib.__version__

>>> import construct
>>> print contruct.__version__

Update: This is the approach recommended by PEP 396. But that PEP was never accepted and has been deferred. In fact, there appears to be increasing support amongst Python core developers to recommend not including a __version__ attribute, e.g. in

How to check version of Python modules

Python >= 3.8:

If youre on python >=3.8 you can use a module from the built-in library for that. To check a packages version (in this example construct) run:

>>> from importlib.metadata import version
>>> version(construct)

Python < 3.8:

Use pkg_resources module distributed with setuptools library. Note that the string that you pass to get_distribution method should correspond to the PyPI entry.

>>> import pkg_resources
>>> pkg_resources.get_distribution(construct).version

Side notes:

  1. Note that the string that you pass to the get_distribution method should be the package name as registered in PyPI, not the module name that you are trying to import. Unfortunately, these arent always the same (e.g. you do pip install memcached, but import memcache).

  2. If you want to apply this solution from the command line you can do somthing like:

python -c 
  import pkg_resources; print(pkg_resources.get_distribution(construct).version)

Leave a Reply

Your email address will not be published. Required fields are marked *