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?

- 57,944
- 17
- 167
- 143

- 2,270
- 7
- 27
- 37
9 Answers
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)

- 22,280
- 12
- 56
- 83
-
1As a bonus, this automatically recursively detects conflicting version requirements -- these would be unsatisfiable. – Asclepius Aug 03 '17 at 03:43
-
4Loop over the require call with a try: except pkg_resources.DistributionNotFound wrapping the call. Then on exception you print. This way it'll tell you all missing dependencies and not die on the first missing one found. – Shardj Jul 13 '18 at 11:31
-
The update links to Asclepius's answer. However, it doesn't use `distutils.text_file.TextFile` like the text of this answer indicates. – Flimm Feb 11 '22 at 14:06
Based on the answer by Zaur, assuming you indeed use a requirements file, you may want a unit test, perhaps in tests/test_requirements.py
, that confirms the availability of packages.
Moreover, this approach uses a subtest to independently confirm each requirement. This is useful so that all failures are documented. Without subtests, only a single failure is documented.
"""Test availability of required packages."""
import unittest
from pathlib import Path
import pkg_resources
_REQUIREMENTS_PATH = Path(__file__).parent.with_name("requirements.txt")
class TestRequirements(unittest.TestCase):
"""Test availability of required packages."""
def test_requirements(self):
"""Test that each required package is available."""
# Ref: https://stackoverflow.com/a/45474387/
requirements = pkg_resources.parse_requirements(_REQUIREMENTS_PATH.open())
for requirement in requirements:
requirement = str(requirement)
with self.subTest(requirement=requirement):
pkg_resources.require(requirement)

- 57,944
- 17
- 167
- 143
-
1
-
1
-
1@R.Ilma With subtests you can know exactly the full subset of requirements that failed, so it's frequently useful while testing. Without subtests, you only know the first failure. – Asclepius Dec 16 '19 at 18:02
-
When I run the test I get the error `AttributeError: module 'distutils' has no attribute 'text_file'` when I did check the `distutils` source code I didn't find `text_file`, I'm using Python 3.6.9 – Bilal Mar 01 '20 at 13:04
-
@Acumenus, thank you for your prompt reply, I just added [some details here](https://stackoverflow.com/a/60475507/4488332) with the solution I found. (sorry I did a mistake in the Python version, it's 3.6.9) – Bilal Mar 01 '20 at 13:25
-
Instead of `distutils.text_file.TextFile`, one could use [_setuptools_ own `pkg_resources.parse_requirements`](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#requirements-parsing), like in this example: https://stackoverflow.com/a/59971236/11138259 – sinoroc Apr 08 '20 at 06:36
-
3@sinoroc Actually this answer used to use `pkg_resources.parse_requirements` as you can confirm in its edit history. I had to stop using it because its API was extremely wonky and used to keep breaking all the time. Now I have edited the answer again to go back to using it as per your suggestion. – Asclepius Apr 09 '20 at 19:50
-
I see, I think I'd already been told before that for a while that API was somewhat untrustworthy, don't remember the exact details anymore. Anyway, I appreciate when people make the effort to keep their answers up-to-date, thanks. – sinoroc Apr 09 '20 at 19:58
-
-
2@Juan-Kabbali Even if it's possible, it's very non-standard. The packages are supposed to be managed by a package manager, e.g. pip, poetry, conda, etc., so the same package would have to be run. The standard workflow, however, is to first install the defined list of packages (as per the usage instructions of the chosen package manager), and only then run the unit tests. – Asclepius Apr 28 '20 at 17:30
-
One thing this doesn't handle are referenced files (e.g. `-r requirements.txt` in a requirements-dev.txt file). This produces a parse error and requires a little more work to make it work. – Sam Bull Dec 12 '20 at 20:38
-
@SamBull Noted, but then I have littler reason to reference `requirements.txt` in `requirements-dev.txt` because I can use `pip install -U -r ./requirements.txt -r ./requirements-dev.txt` to install both via a single command. – Asclepius Dec 12 '20 at 21:11
-
Thank you very much for this answer which helped me a lot. While trying to understand the code, I saw that `pkg_resources` has become deprecated according to the [setuptools documentation](https://setuptools.pypa.io/en/latest/pkg_resources.html) and must be replaced by `importlib`, however I can't find any function equivalent to parse_requirements in this library, any ideas? – Alexandre Novius May 16 '23 at 09:37
You can run pip freeze
to see what you have installed and compare it to your requirements.txt
file.
If you want to install missing modules you can run pip install -r requirements.txt
and that will install any missing modules and tell you at the end which ones were missing and installed.

- 57,944
- 17
- 167
- 143

- 11,069
- 12
- 51
- 60
Here's a one-liner based on Zaur Nasibov's answer for if you don't care to know which packages are not installed:
python3 -c "import pkg_resources; pkg_resources.require(open('requirements.txt',mode='r'))" &>/dev/null
Whether the command finishes successfully can then be used to do a pip install.
As an equivalent to Ruby's bundle check || bundle install
, we're doing:
python3 -c "import pkg_resources; pkg_resources.require(open('requirements.txt',mode='r'))" &>/dev/null || pip3 install --ignore-installed -r requirements.txt
I realise this is not addressing the exact question, but this page comes up first when Googling for that. And anyway, you'd only really be wanting to know what the missing dependencies are in order to then satisfy them.
We can't just use pip3 check
for this, since it does not look at the requirements.txt

- 485
- 3
- 7
If you're interested in doing this from the command line, pip-missing-reqs
will list missing packages. Example:
$ pip-missing-reqs directory
Missing requirements:
directory/exceptions.py:11 dist=grpcio module=grpc
(pip check
and pipdeptree --warn fail
only audit installed packages for compatibility with each other, without checking requirements.txt
.)

- 146
- 7
-
2`pip check` does not verify the packages in a requirements file are installed. `pip check` verifies that already installed packages have compatible/non-broken dependencies. – compman2408 Sep 18 '19 at 18:45
You can use the -r
option from pip freeze
that verifies that. It generates a WARNING
log for packages that are not installed. One appropriated verbose mode should be selected in order the WARNING
message to be shown. For example:
$ pip -vvv freeze -r requirements.txt | grep "not installed"
WARNING: Requirement file [requirements.txt] contains six==1.15.0, but package 'six' is not installed

- 4,431
- 3
- 34
- 42
-
This works, but not for the obvious reason (at least for pip version 23.0.1). pip outputs to stdout a series of messages, none of which match `not installed`, so all of the output sent to stdout is discarded. In addition pip outputs to stderr the Warning messages. So a more efficient thing to use is `pip freeze -r requirements.txt > /dev/null`. – icarus Apr 17 '23 at 01:44
Running
pip freeze -r requirements.txt
it will compare installed ones to the requirements file and warn you which ones are not

- 124
- 6
In addition to check whether modules listed in requirements.txt
are installed, you may want to check whether all used modules by your project are indeed listed in the requirements.txt
file.
If you are using flake8 for style-checking, you can add flake8-requirements plugin for flake8. It will automatically check whether imported modules are available in setup.py
, requirements.txt
or pyproject.toml
file. Additionally, for custom modules you can add custom configuration with known-modules (in order to prevent flake8 warnings). For more configuration options, see flake8-requirements project's description.

- 46
- 5
Answer by Asclepius revisited to avoid using the pkg_resources library which is now deprecated. I don't have much experience with pip, so it probably has errors in this code, but it gave very similar results to the original answer.
"""Test availability of required packages."""
import unittest
from pathlib import Path
from pip._internal.req.req_file import parse_requirements
from pip._internal.req.constructors import install_req_from_parsed_requirement
from pip._internal.network.session import PipSession
from pip._internal.exceptions import DistributionNotFound
_REQUIREMENTS_PATH = Path(__file__).parent.with_name("requirements.txt")
class TestRequirements(unittest.TestCase):
"""Test availability of required packages."""
def test_requirements(self):
"""Test that each required package is available."""
# Ref: https://stackoverflow.com/a/45474387/
session = PipSession()
requirements = parse_requirements(str(_REQUIREMENTS_PATH), session)
for requirement in requirements:
req_to_install = install_req_from_parsed_requirement(requirement)
req_to_install.check_if_exists(use_user_site=False)
with self.subTest(req_to_install=str(req_to_install)):
if not req_to_install.satisfied_by:
raise DistributionNotFound()

- 172
- 7