Check if my Python has all required packages

Alagappan Ramu picture Alagappan Ramu · Apr 30, 2013 · Viewed 31.8k times · Source

I have a requirements.txt file with a list of packages that are required for my virtual environment. Is it possible to find out whether all the packages mentioned in the file are present. If some packages are missing, how to find out which are the missing packages?

Answer

Zaur Nasibov picture Zaur Nasibov · Apr 30, 2013

UPDATE:

An up-to-date and improved way to do this is via distutils.text_file.TextFile. See Acumenus' answer below for details.

ORIGINAL:

The pythonic way of doing it is via the pkg_resources API. The requirements are written in a format understood by setuptools. E.g:

Werkzeug>=0.6.1
Flask
Django>=1.3

The example code:

import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

# dependencies can be any iterable with strings, 
# e.g. file line-by-line iterator
dependencies = [
  'Werkzeug>=0.6.1',
  'Flask>=0.9',
]

# here, if a dependency is not met, a DistributionNotFound or VersionConflict
# exception is thrown. 
pkg_resources.require(dependencies)