1027

I installed the Python modules construct and statlib using setuptools:

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

How do I check their versions from the command line?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
tarabyte
  • 17,837
  • 15
  • 76
  • 117

31 Answers31

1053

Use pip instead of easy_install.

With pip, list all installed packages and their versions via:

pip freeze

On 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:

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. I strongly advise to take look into Python virtual environment managers, for example virtualenvwrapper.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
alko
  • 46,136
  • 12
  • 94
  • 102
  • 28
    an answer below suggested `pip show lxml | grep Version` ; this will run much faster, since it only inspects a single package. – Jonathan Vanasco Dec 02 '14 at 17:01
  • 14
    Just for completeness: A third version is `pip list | grep lxml` – 0xAffe Jul 13 '15 at 07:45
  • 3
    How about on Windows system? What is the `grep` in windows? Since pip freeze | grep lxml doesn't work on windwos. – Raven Cheuk Oct 03 '18 at 07:42
  • 8
    @RavenCheuk use `pip list | findstr lxml` – Alex F Oct 12 '18 at 15:32
  • 2
    windows variant with find (1 character shorter...): pip list | find "lxml" – Jordan Stefanelli Feb 04 '19 at 17:10
  • ```pip freeze | grep keras``` did not show the version of installed keras, but ```pip show keras | grep Version``` did show. That means ```pip freeze | grep library name``` cannot be used for all libraries. – YatShan Jun 11 '19 at 00:54
  • I seem to be getting a discrepancy in output: >>print(sklearn.__version__) #returns 0.20.3 >>pip show sklearn #return 0.0; can you clarify? – Sumax Jul 24 '19 at 09:19
  • 1
    Unfortunately this does not cover many cases :( . Look at this answer: https://stackoverflow.com/a/56912343/7262247 . It includes the method that you suggest ('pip' package info and module `__version__` ) but also covers many more – smarie Jan 29 '20 at 17:16
  • `'grep' is not recognized as an internal or external command, operable program or batch file.` – Nouman May 27 '20 at 05:06
  • This isn't working when the version is defined in a setuptools.setup function, is there a way to do it? – pgp1 Jun 12 '20 at 08:17
502

You can try

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

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

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 Remove importlib_metadata.version..

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • 76
    Some versions of some common libraries (such as `inspect`) not not have a `__version__` attribute, unfortunately. – ely Feb 26 '14 at 13:42
  • 6
    PySerial has `serial.VERSION`. Maybe there are some other commonly used modules as well, which aren't following PEP 0396: https://www.python.org/dev/peps/pep-0396/ – Sussch Nov 30 '15 at 10:15
  • 9
    a lot of modules do not have __version__ – sdaffa23fdsf Jan 15 '16 at 23:49
  • 1
    @sdaffa23fdsf which modules do not have version? More than serial, inspect, PyQt and SQLite? See [pycmake](https://github.com/Statoil/pycmake/blob/master/pycmake.cmake). – Pål GD Jul 11 '16 at 08:30
  • +1 because this works on any OS. Even if some modules do not have a __version__ attribute, this is by far the easiest. – RolfBly Jul 13 '16 at 18:59
  • I get > " module has no attribute version" with serial.VERSION on Python 2.7 ! – AAI Aug 22 '17 at 20:53
  • 8
    `print(contruct.__version__)` if using Python 3.* – jacanterbury Nov 05 '18 at 16:19
  • I seem to be getting a discrepancy in output: >>print(sklearn.__version__) #returns 0.20.3 >>pip show sklearn #return 0.0; can you clarify? – Sumax Jul 24 '19 at 09:19
  • Beware that PEP 396 was never accepted and has been deferred: python.org/dev/peps/pep-0396 – Nzbuu Oct 22 '20 at 14:49
  • You don't even need the `print` part, as this example shows: https://stackoverflow.com/a/59631210/4561887. Just `import yaml` and then `yaml.__version__` is enough, for instance, in a live Python interactive session. – Gabriel Staples Jan 30 '21 at 01:18
  • Re *"contruct"*: Not *"construct"*? (with an "s"). In any case, it makes it easier to see [who has plagiarised your answer](https://stackoverflow.com/questions/20180543/how-to-check-the-version-of-python-modules/59631210#59631210)! – Peter Mortensen Apr 07 '22 at 23:21
415

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 something like:

python -c \
  "import pkg_resources; print(pkg_resources.get_distribution('construct').version)"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jakub Kukul
  • 12,032
  • 3
  • 54
  • 53
  • 36
    This works even if the module does not have the attribute `__version__`. – imranal Nov 10 '15 at 10:17
  • What about this? ``construct.version.full_version`` – MyounghoonKim Aug 07 '16 at 14:03
  • 13
    Should be the top answer, it's the only reliable way of getting the package version (if there is one) – henryJack Jan 15 '18 at 11:53
  • Looks like this plays nicely with the version you specify in setuptools's `setup` call. Thanks! – Matt Messersmith Feb 14 '18 at 18:19
  • 7
    Note that `pkg_resources.get_distrinbution` does not always work either. It issues some `DistributionNotFound` exception with error message like : "The 'the_package_name' distribution was not found and is required by the application" – mjv Apr 06 '18 at 23:37
  • So far this is the best solution working with **pbr** packager. Thank you! – nad2000 May 29 '18 at 23:38
  • 4
    @mjv your error most likely occurs because 1) the package is not installed 2) you're passing a module name instead of a package name to the `get_distribution` method – Jakub Kukul Feb 24 '19 at 15:08
  • 1
    For Python < 3.8 I think you should recommend `importlib_metadata` over `pkg_resources`, it will be more consistent with how stdlib `importlib.metadata` works. – wim Oct 07 '20 at 06:34
  • 1
    @wim thanks for the suggestion, I also thought about it. I decided to stick with `pkg_resources` for now, because you're more likely to have it already installed (via `setuptools`). `importlib_metadata` needs to be installed separately, so I think there's a bit more friction. – Jakub Kukul Oct 08 '20 at 12:36
  • Importing packages can be costly, just reading package meta information therefore can be beneficial. – normanius Apr 16 '21 at 22:21
  • This should be the correct answer. Works across different OSes and doesn't require importing the packages, just to see their versions. – MGLondon Apr 30 '21 at 09:08
  • @wim I'm trying both and it seems that if you have installed several versions of one project and not purge everything `importlib_metadata` is **not reliable**, since it will get the first of the `distributions` it finds instead of the one being used. I find that `pkg_resources` is showing the "at use" version. – Aru Díaz Feb 16 '22 at 11:07
  • 1
    @AlejandroDíaz How are you installing multiple versions of the same package in the first place, these days? `pip` won't do it, and [`easy_install`](https://setuptools.pypa.io/en/latest/deprecated/easy_install.html) along with it's multi-installs has been deprecated since 2019.. – wim Feb 17 '22 at 04:58
  • @wim sorry, I may have lead to a misunderstanding! What I mean is, you work on a project, you keep updating over time its deps but without uninstalling previous version, the whole of the dist infos are kept in the `site-packages` right? So `distributions` is going to get one of those, but not specifically the one that is currently in use, so that's not a reliable way to get it – Aru Díaz Feb 17 '22 at 11:39
  • No, those dist-info dirs would not be left around in site-packages, generally. They should be removed when you install updated version, because pip will uninstall the old package before installing a different version. – wim Feb 17 '22 at 12:54
  • this is not working in python 3.9.2 – Jasen Oct 17 '22 at 22:37
171

Use pip show to find the version!

# In order to get the package version, execute the below command
pip show YOUR_PACKAGE_NAME | grep Version

You can use pip show YOUR_PACKAGE_NAME - which gives you all details of package. This also works in Windows.

grep Version is used in Linux to filter out the version and show it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0x3bfc
  • 2,715
  • 1
  • 16
  • 20
  • 2
    No joy here! `pip: error: No command by the name pip show (maybe you meant "pip install show")` – Sam Finnigan Apr 05 '15 at 10:46
  • This answer is only really suitable if you need a package version from the shell. If you need it within Python, this would be a pretty bad hack. Anyways, you can use the following command to extract the version: `pip show PACKAGE | awk '/^Version: / {sub("^Version: ", ""); print}'`. You could probably get away with a simpler AWK script, but the aforementioned will be safer for any edge cases. – Six Oct 02 '15 at 12:09
  • 6
    @SamFinnigan `pip show` was implemented in *pip 1.2.1.post1*. You are using a terribly dated version of pip so no wonder you're having trouble! I'm currently running *pip 7.1.2*. If something is preventing you from updating, you can always just install it locally or in a virtualenv. – Six Oct 02 '15 at 12:13
  • has worked for me thanks. some of the packeges have not .__version__ parameter so that one is more useful. – Salih Karagoz Apr 13 '18 at 06:56
  • I seem to be getting a discrepancy in output: >>print(sklearn.__version__) #returns 0.20.3 >>pip show sklearn #return 0.0; can you clarify? – Sumax Jul 24 '19 at 09:18
  • 1
    `'grep' is not recognized as an internal or external command, operable program or batch file.` – Nouman May 27 '20 at 05:06
  • This appears to install a totally unrelated package [show](https://pypi.org/project/show/) (as root!). That command is not "in order to run `pip show`", pip has had a show subcommand for as long as I remember. How did this get 100 upvotes!? – wim Oct 07 '20 at 06:37
  • you can actually use `pip show YOUR_PACKAGE_NAME` to get all the details of the package. Works in Windows. `grep Version` is to get the version only and ignore other details. – Gangula Feb 24 '22 at 12:28
  • On some systems, it may be `pip3 show` instead of `pip show`. – Peter Mortensen Mar 27 '22 at 19:59
  • @Black Thunder: On what system (incl. versions)? – Peter Mortensen Mar 27 '22 at 20:00
  • Using `pip show` is not the most reliable way because people often get confused by multiple installations of python, pip, virtual envs, etc. For real debugging, you need to check the version inside python code. See https://stackoverflow.com/questions/20180543/how-do-i-check-the-versions-of-python-modules/32965521#32965521 – wisbucky Jan 18 '23 at 17:08
119

The better way to do that is:


For the details of a 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: numpy-discussion@python.org
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:

For more details: >>> pip help


pip should be updated to do this.

pip install --upgrade pip

On Windows the recommended command is:

python -m pip install --upgrade pip
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
susan097
  • 3,500
  • 1
  • 23
  • 30
  • I seem to be getting a discrepancy in output: >>print(sklearn.__version__) #returns 0.20.3 >>pip show sklearn #return 0.0; can you clarify? – Sumax Jul 24 '19 at 09:16
  • 3
    You should use `pip show scikit-learn` instead of `pip show sklearn`. sklearn is short form used during import, not recognize directly in `pip` since `scikit-learn` is the full package learn not `sklearn` – susan097 Jul 24 '19 at 09:54
  • Using `pip show` is not the most reliable way because people often get confused by multiple installations of python, pip, virtual envs, etc. For real debugging, you need to check the version inside python code. See https://stackoverflow.com/questions/20180543/how-do-i-check-the-versions-of-python-modules/32965521#32965521 – wisbucky Jan 18 '23 at 17:08
55

In Python 3 with brackets around print:

>>> import celery
>>> print(celery.__version__)
3.1.14
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user224767
  • 979
  • 8
  • 4
  • 35
    Not every package has a `__version__` attribute. – Spedwards Apr 15 '15 at 10:12
  • 2
    This answer is for python 3 - which is a different language. However, you can use this answer in python 2. To do so requires adding the line: "from __future__ import print_function", before the other statements. – user1976 Jun 21 '16 at 09:07
  • 2
    @user1976 This is valid syntax in Python 2 as well. The parentheses are simply tolerated around the argument to `print`, just like `(2)+(3)` evaluates to `5`. When you have a comma inside the parentheses, things may get marginally more interesting, though for `print`, it still works, sort of. – tripleee Jul 28 '16 at 10:28
  • This answer does not contribute any new insights compared to older answers. – normanius Apr 16 '21 at 22:27
27

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:

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', ...]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
waterproof
  • 4,943
  • 5
  • 30
  • 28
  • 1
    Yes, not all package creators set __version__, but if you're using `pip`, this should always work. – waterproof Apr 09 '18 at 15:35
  • 2
    Unfortunately, this solution isn't viable. Pip doesn't guarantee any in-process API, only an API through the command-line. This approach no longer works on pip 10. – Jason R. Coombs May 12 '18 at 12:47
23

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

Here is an example from the documentation:

>>> from importlib.metadata import version
>>> version('requests')
'2.22.0'
Davit Tovmasyan
  • 3,238
  • 2
  • 20
  • 36
21

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__ 
tashuhka
  • 5,028
  • 4
  • 45
  • 64
  • 4
    This just avoids attempting to print `__version__` if it not defined. If there is no `__version__`, you receive no result for the package you want. – tripleee Jul 28 '16 at 10:25
  • If the module does no have a `__version__` attribute, which is the standard (https://www.python.org/dev/peps/pep-0396/#specification), it is impossible to know where and how the version is included without manual investigation. – tashuhka Feb 11 '17 at 15:41
  • An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/29770964/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 07 '22 at 22:44
15

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']
jturi
  • 1,615
  • 15
  • 11
14

You can try this:

pip list

This will output all the packages with their versions.

Output

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CRBelhekar
  • 341
  • 3
  • 6
11

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

Yuchao Jiang
  • 3,522
  • 30
  • 23
9

If the methods in previous answers do not work, it is worth trying the following in Python:

import modulename

modulename.version
modulename.version_info

See Get the Python Tornado version

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
D A
  • 3,130
  • 4
  • 25
  • 41
8

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
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user10429366
  • 81
  • 1
  • 1
7

First add executables python and 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
suraj garla
  • 322
  • 3
  • 6
7

I suggest opening a Python shell in the 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 Python 3.8 can (surely will) give a different version of a library than opening with Python 3.5 or Python 2.7.

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
loved.by.Jesus
  • 2,266
  • 28
  • 34
7

This answer is 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, you can simply do:

  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 interpreter on your system, the PyPI packages are normally visible in the directory/folder: PythonLibsite-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 example: I had to know the version of a pre-installed module named "Selenium-Screenshot". It correctly showed as 1.5.0:

Command prompt screenshot

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lousycoder
  • 451
  • 6
  • 10
7

Go to terminal like pycharm-terminal

Now write py or python and hit Enter.

Now you are inside python in the terminal you can try this way:

# import <name_of_the_library>

import kivy

# So if the library has __version__ magic method, so this way will help you

kivy.__version__  # then hit Enter to see the version

# Output >> '2.1.0'

but if the above way not working for you can try this way to know information include the version of the library

 pip show module <HERE PUT THE NAME OF THE LIBRARY>

Example:

pip show module pyperclip

Output:
       Name: pyperclip
       Version: 1.8.2
       Summary: A cross-platform clipboard module for Python. (Only handles plain text for now.)
       Home-page: https://github.com/asweigart/pyperclip
       Author: Al Sweigart
       Author-email: al@inventwithpython.com
       License: BSD
       Location: c:\c\kivymd\virt\lib\site-packages
       Requires:
       Required-by:

There is another way that could help you to show all the libraries and versions of them inside the project:

pip freeze
# I used the above command in a terminal inside my project this is the output
       certifi==2021.10.8
       charset-normalizer==2.0.12
       docutils==0.18.1
       idna==3.3
       Kivy==2.1.0
       kivy-deps.angle==0.3.2
       kivy-deps.glew==0.3.1
       kivy-deps.sdl2==0.4.5
       Kivy-Garden==0.1.5
       kivymd @ file:///C:/c/kivymd/KivyMD
       Pillow==9.1.0
       Pygments==2.12.0
       pyperclip==1.8.2
       pypiwin32==223
       pywin32==303
       requests==2.27.1
       urllib3==1.26.9

and sure you can try using the below command to show all libraries and their versions

pip list

Hope to Help anyone, Greetings

5

In summary:

conda list

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

And:

pip show tensorflow

(It gives complete library details.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tejj
  • 161
  • 1
  • 7
4

This works in Jupyter Notebook on Windows, too! As long as Jupyter is launched from a Bash-compliant command line such as Git Bash (Mingw-w64), 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: lxml-dev@lxml.de
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires:
Required-by: jupyter-contrib-nbextensions
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karl Baker
  • 903
  • 12
  • 27
4

After scouring the Internet, trying to figure out how to ensure the version of a module I’m running (apparently python_is_horrible.__version__ isn’t a thing in Python 2?) across operating systems and Python versions... literally none of these answers worked for my scenario...

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

assumes the module is already installed and can be imported


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

Python 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 that’s it...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carl Boneri
  • 2,632
  • 1
  • 13
  • 15
  • note: not all packages have a `.version` attribute `sys.modules.get("numpy").version` – Kermit Jan 30 '21 at 15:16
  • 1
    @HashRocketSyntax for the life of me I can't understand why there isn't more uniformity with both this, and the import model for python modules/packages. Constant headache – Carl Boneri Jan 30 '21 at 23:58
2

A Python program to list all packages (you can copy it to file 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yarh
  • 895
  • 7
  • 15
2

(See also How do I get the version of an installed module in Python programmatically?)

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
smarie
  • 4,568
  • 24
  • 39
1

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?

Tobias Bleisch
  • 133
  • 1
  • 7
1

I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no global 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'
Majte
  • 264
  • 2
  • 9
1

And in case your production 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
[..]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mirekphd
  • 4,799
  • 3
  • 38
  • 59
1

Here's a small Bash program to get the version of any package in your Python environment. Just copy this to your /usr/bin and provide it with executable permissions:

#!/bin/bash
packageName=$1

python -c "import ${packageName} as package; print(package.__version__)"

Then you can just run it in the terminal, assuming you named the script py-check-version:

py-check-version whatever_package
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aleksandar Jovanovic
  • 1,127
  • 1
  • 11
  • 14
1

For situations where field __version__ is not defined:

try:
    from importlib import metadata
except ImportError:
    import importlib_metadata as metadata # python<=3.7

metadata.version("package")

Alternatively, and like it was already mentioned:

import pkg_resources
pkg_resources.get_distribution('package').version
renatodamas
  • 16,555
  • 8
  • 30
  • 51
0

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 in the right direction.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alessio Arena
  • 390
  • 2
  • 8
-1

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 the package version.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shaina Raza
  • 1,474
  • 17
  • 12
  • `__version__` attribute is already mentioned in many other answers here, what new information is this answer contributing? – wim Oct 07 '20 at 06:42
-1

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:

subprocess — Subprocess management

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DogeCode
  • 346
  • 2
  • 10
  • This is the python version itself, the question is asking about package versions. – wim Oct 07 '20 at 06:41