807
votes

I just installed the python modules: construct and statlib with setuptools like this:

# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

I want to be able to (programmatically) check their versions. Is there an equivalent to python --version I can run from the command line?

My python version is 2.7.3.

28
For those interested by a command line solution, use: pip listKrisWebDev

28 Answers

871
votes

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 you're interested in:

Linux:
$ pip freeze | grep lxml
lxml==2.3

Windows:
c:\> pip freeze | findstr lxml
lxml==2.3

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

$ python -c "import requests; print(requests.__version__)"
2.14.2
$ 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 you're installing to the global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper

424
votes

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 https://gitlab.com/python-devs/importlib_metadata/-/merge_requests/125.

287
votes

Python >= 3.8:

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

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

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
'2.5.2'

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 aren't 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)"
106
votes

Use pip show to find the version!

# in order to get package version execute the below command
pip show YOUR_PACKAGE_NAME | grep Version
96
votes

The Better way to do that is:


For the details of specific Package

pip show <package_name>

It details out the Package_name, Version, Author, Location etc.


$ pip show numpy
Name: numpy
Version: 1.13.3
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: [email protected]
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:

For more Details: >>> pip help


pip
pip install --upgrade pip

On Windows recommend command is:

python -m pip install --upgrade pip

44
votes

In python3 with brackets around print

>>> import celery
>>> print(celery.__version__)
3.1.14
22
votes

module.__version__ is a good first thing to try, but it doesn't always work.

If you don't want to shell out, and you're using pip 8 or 9, you can still use pip.get_installed_distributions() to get versions from within Python:

update: the solution here works in pip 8 and 9, but in pip 10 the function has been moved from pip.get_installed_distributions to pip._internal.utils.misc.get_installed_distributions to explicitly indicate that it's not for external use. It's not a good idea to rely on it if you're using pip 10+.

import pip

pip.get_installed_distributions()  # -> [distribute 0.6.16 (...), ...]

[
    pkg.key + ': ' + pkg.version
    for pkg in pip.get_installed_distributions()
    if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]
16
votes

The previous answers did not solve my problem, but this code did:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__ 
12
votes

Use dir() to find out if the module has a __version__ attribute at all.

>>> import selenium
>>> dir(selenium)
['__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '__path__', '__version__']
>>> selenium.__version__
'3.141.0'
>>> selenium.__path__
['/venv/local/lib/python2.7/site-packages/selenium']
8
votes

In Python 3.8 version there is a new metadata module in importlib package, which can do that as well.

Here is an example from docs:

>>> from importlib.metadata import version
>>> version('requests')
'2.22.0'
7
votes

If the above methods do not work, it is worth trying the following in python:

import modulename

modulename.version
modulename.version_info

See Get Python Tornado Version?

Note, the .version worked for me on a few others besides tornado as well.

6
votes

first add python, pip to your environment variables. so that you can execute your commands from command prompt. then simply give python command. then import the package

-->import scrapy

then print the version name

-->print(scrapy.__version__)

This will definitely work

6
votes

Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):

1) if the package (e.g. xgboost) was installed with pip:

!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost

2) if the package (e.g. caffe) was installed with conda:

!conda list caffe
5
votes

Some modules don't have __version__ attribute, so the easiest way is check in the terminal: pip list

5
votes

I suggest opening a python shell in terminal (in the python version you are interested), importing the library, and getting its __version__ attribute.

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

Note 1: We must regard the python version. If we have installed different versions of python, we have to open the terminal in the python version we are interested in. For example, opening the terminal with python3.8 can (surely will) give a different version of a library than opening with python3.5 or python2.7.

Note 2: We avoid using the print function, because its behavior depends on python2 or python3. We do not need it, the terminal will show the value of the expression.

5
votes

You can try this:

pip list

This will output all the packages with their versions. Output

4
votes

Writing this answer for windows users. As suggested in all other answers, you can use the statements as:

import [type the module name]
print(module.__version__)      # module + '.' + double underscore + version + double underscore

But, there are some modules which don't print their version even after using the method above. So, what you can simply do is:

  1. Open the command prompt.
  2. Navigate to the file address/directory by using cd [file address] where you've kept your python and all supporting modules installed. If you have only one python on your system, the PYPI packages are normally visible in the directory/folder:- Python > Lib > site-packages.
  3. use the command "pip install [module name]" and hit enter.
  4. This will show you a message as "Requirement already satisfied: file address\folder name (with version)".
  5. See the screenshot below for ex: I had to know the version of a pre-installed module named as "Selenium-Screenshot". It showed me correctly as 1.5.0:

command prompt screenshot

3
votes

In Summary:

conda list   

(It will provide all the libraries along with version details).

And:

pip show tensorflow

(It gives complete library details).

2
votes

This works in Jupyter Notebook on Windows, too! As long as Jupyter is launched from a bash-compliant command line such as Git Bash (MingW64), the solutions given in many of the answers can be used in Jupyter Notebook on Windows systems with one tiny tweak.

I'm running windows 10 Pro with Python installed via Anaconda, and the following code works when I launch Jupyter via Git Bash (but does not when I launch from the Anaconda prompt).

The tweak: Add an exclamation mark (!) in front of pip to make it !pip.

>>>!pip show lxml | grep Version
Version: 4.1.0

>>>!pip freeze | grep lxml
lxml==4.1.0

>>>!pip list | grep lxml
lxml                               4.1.0                  

>>>!pip show lxml
Name: lxml
Version: 4.1.0
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: [email protected]
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires: 
Required-by: jupyter-contrib-nbextensions
2
votes

Quick python program to list all packges (you can copy it to requirements.txt)

from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key): 
    print_log +=  module.key + '~=' + module.version  + '\n'
print(print_log)

The output would look like:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98
2
votes

(see also https://stackoverflow.com/a/56912280/7262247)

I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by Jakub Kukul' answer), as most of them do not cover all cases. For example

  • built-in modules
  • modules not installed but just added to the python path (by your IDE for example)
  • two versions of the same module available (one in python path superseding the one installed)

Since we needed a reliable way to get the version of any package, module or submodule, I ended up writing getversion. It is quite simple to use:

from getversion import get_module_version
import foo
version, details = get_module_version(foo)

See the documentation for details.

1
votes

To get a list of non-standard (pip) modules imported in the current module:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

Result:

>>> import sys, pip, nltk, bs4
>>> [{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() if pkg.key in set(sys.modules) & set(globals())]
[{'pip': '9.0.1'}, {'nltk': '3.2.1'}, {'bs4': '0.0.1'}]

Note:

This code was put together from solutions both on this page and from How to list imported modules?

1
votes

After scouring the internet trying to figure out how to ensure the version of a module im running (apparently python_is_horrible.__version__ isnt a thing in 2?) across os's and python versions... literally none of these answers worked for my scenario...

Then i thought about it a minute and realized the basics... after ~30mins of fails...

assumes the module is already installed and can be imported


3.7

>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'3.7.2'

2.7

>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'2.7.11'

literally thats it...

0
votes

Building on Jakub Kukul's answer I found a more reliable way to solve this problem.

The main problem of that approach is that requires the packages to be installed "conventionally" (and that does not include using pip install --user), or be in the system PATH at Python initialisation.

To get around that you can use pkg_resources.find_distributions(path_to_search). This basically searches for distributions that would be importable if path_to_search was in the system PATH.

We can iterate through this generator like this:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

This will return a dictionary having modules as keys and their version as value. This approach can be extended to a lot more than version number.

Thanks to Jakub Kukul for pointing to the right direction

0
votes

I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no glove solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.

import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
    modules_version = f.read()
  
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}

Retrieve your module's versions through passing the module label key, e.g.:

>>  module_dict["seaborn"]
'0.9.0'
0
votes

And in case your prod system is hardened beyond comprehension so it has neither pip nor conda, here is a bash replacement for pip freeze:

ls /usr/local/lib/python3.8/dist-packages | grep info | awk -F "-" '{print $1"=="$2}' | sed 's/.dist//g'

(make sure you update your dist-packages folder to your current python version and ignore inconsistent names, e.g. underscores vs. dashes).

Sample printout:

Flask==1.1.2
Flask_Caching==1.10.1
gunicorn==20.1.0
[..]
-1
votes

You can simply use subprocess.getoutput(python3 --version)

import subprocess as sp
print(sp.getoutput(python3 --version))

# or however it suits your needs!
py3_version = sp.getoutput(python3 --version)

def check_version(name, version):...

check_version('python3', py3_version)

For more information and ways to do this without depending on the __version__ attribute:

Assign output of os.system to a variable and prevent it from being displayed on the screen

You can also use subprocess.check_output() which raises an error when the subprocess returns anything other than exit code 0:

https://docs.python.org/3/library/subprocess.html#check_output()

-2
votes

you can first install some package like this and then check its version

pip install package
import package
print(package.__version__)

it should give you package version