How do I check the versions of Python modules?
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.
How do I get a python module's version number through code?
Generalized answer from Matt's, do a dir(YOURMODULE)
and look for __version__
, VERSION
, or version
. Most modules like __version__
but I think numpy
uses version.version
How do I see what Python modules are installed, and what version?
Looks like all you need is the pip list
command on your terminal
Checking a Python module version at runtime
I'd stay away from hashing. The version of libxslt being used might contain some type of patch that doesn't effect your use of it.
As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not). For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.
For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect. Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.
How to check version of python package if no __version__ variable is set
It does have the version info, just use .version
:
In [4]: pyodbc.version
Out[4]: '3.0.10'
The pip show command would also get it for you:
In [54]: pip.main(["show","pyodbc"])
---
Metadata-Version: 1.1
Name: pyodbc
Version: 3.0.10
Summary: DB API Module for ODBC
Home-page: http://code.google.com/p/pyodbc
Author: Michael Kleehammer
Author-email: michael@kleehammer.com
License: MIT
Location: /usr/local/lib/python2.7/dist-packages
Requires:
Classifiers:
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
Intended Audience :: System Administrators
License :: OSI Approved :: MIT License
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 3
Topic :: Database
Out[54]: 0
You could redirect stdout and parse the output:
import pip
import sys
if sys.version_info.major >= 3:
from io import StringIO
else:
from StringIO import StringIO
def get_version(package):
f = StringIO()
sys.stdout = f
pip.main(["show", package])
sys.stdout = sys.__stdout__
return next((line.split(":", 1)[1].strip()
for line in f.getvalue().splitlines() if line.startswith("Version")), "No match")
But an easier way is to use pkg_resources
, if you look at the source for show, you can see how it is gathered:
from pip._vendor import pkg_resources
def get_version(package):
package = package.lower()
return next((p.version for p in pkg_resources.working_set if p.project_name.lower() == package), "No match")
To use it just pass the package name:
In [57]: get_version("pyodbc")
Out[57]: '3.0.10'
In [58]: get_version("pandas")
Out[58]: '0.17.1'
In [59]: get_version("requests")
Out[59]: '2.9.1'
In [60]: get_version("foobar")
Out[60]: 'No match'
You can easily extend it to get different info using similar logic to the show command.
How to check if python package is latest version programmatically?
Fast Version (Checking the package only)
The code below calls the package with an unavailable version like pip install package_name==random
. The call returns all the available versions. The program reads the latest version.
The program then runs pip show package_name
and gets the current version of the package.
If it finds a match, it returns True, otherwise False.
This is a reliable option given that it stands on pip
import subprocess
import sys
def check(name):
latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(name)], capture_output=True, text=True))
latest_version = latest_version[latest_version.find('(from versions:')+15:]
latest_version = latest_version[:latest_version.find(')')]
latest_version = latest_version.replace(' ','').split(',')[-1]
current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)], capture_output=True, text=True))
current_version = current_version[current_version.find('Version:')+8:]
current_version = current_version[:current_version.find('\\n')].replace(' ','')
if latest_version == current_version:
return True
else:
return False
Edit 2021: The code below no longer works with the new version of pip
The following code calls for pip list --outdated
:
import subprocess
import sys
def check(name):
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated'])
outdated_packages = [r.decode().split('==')[0] for r in reqs.split()]
return name in outdated_packages
Find which version of package is installed with pip
As of pip 1.3, there is a pip show
command.
$ pip show Jinja2
---
Name: Jinja2
Version: 2.7.3
Location: /path/to/virtualenv/lib/python2.7/site-packages
Requires: markupsafe
In older versions, pip freeze
and grep
should do the job nicely.
$ pip freeze | grep Jinja2
Jinja2==2.7.3
How to know what python version a package is compatible with
You can look up the package on the Python Package Index and scroll down to the "Meta" section in the left sidebar. This shows the Python version required by the package. As you do not specify the package you are looking for, I will use numpy as an example. For the current version of numpy, the following information is listed:
Requires: Python >=3.7
Therefore, you need Python 3.7 or higher to install this version of numpy.
If you are using an older version of Python and need the most recent version of the package that is compatible with that version, you can go to the release history (the second link at the top of the sidebar) and try different versions, scrolling down to the "Meta" section for every version. This is still a manual process, but less work than trying to install every single version.
Note: often, support for older versions is dropped in larger updates (so when either the first or second version number is updated), so you can skip small updates to speed up your search process.
For example, using this process, you can deduce that numpy 1.19.5 is the latest version to support Python 3.6, and numpy 1.16.6 is the latest version to support Python 2.7. At the top of the page, the command to install an older version of a package is shown, for example: pip install numpy==1.16.6
.
Require a minimum version of a python module
You can use packaging
module. Install it with pip install packaging
and then:
from packaging import version
import pypfopt
ver = pypfopt.__version__
if version.parse(ver) < version.parse('1.2.6'):
logger.error('Version is too low. Update')
Related Topics
How to Build Reports With Python Pandas
How Do Convert a Pandas Dataframe to Xml
How to Locate the Input Within Div
Pandas - Find Index of Value Anywhere in Dataframe
How to Increase the Font Size of the Markdown Table in Jupyter Notebook
Django: Calling .Update() on a Single Model Instance Retrieved by .Get()
How to Display Index During List Iteration With Django
Making Python Dictionary from a Text File With Multiple Keys
Sys.Path Different in Jupyter and Python - How to Import Own Modules in Jupyter
Efficiently Find Repeated Characters in a String
Most Efficient Way to Find Mode in Numpy Array
Create New Column Based on String
Index Out of Bounds Error:Python
Python Multiprocessing Pool Hangs At Join
How to Get Max() to Return Variable Names Instead of Values in Python