Pip freeze for only project requirements

Solution 1:

pipreqs can save the day for a specific project. Just

pip install pipreqs
#then
pipreqs path/to/project

Github Page

Solution 2:

I have tried both pipreqs and pigar and found pigar is better because it also generates information about where it is used, it also has more options.

Solution 3:

I use this command

EDIT: Thanks Addisson Klinke for suggestion

pip freeze -r requirements.txt | grep -B100 "pip freeze" | grep -v "pip freeze"

pip freeze -r requirements.txt | sed '/freeze/,$ d'

When I ran pip freeze -r requirements.txt the output is something like

APScheduler==3.2.0
Eve==0.6.4
Eve-Elastic==0.3.8
## The following requirements were added by pip freeze:
arrow==0.8.0
Cerberus==0.9.2

I have a requirements file like this

APScheduler
Eve
Eve-Elastic

So I get this output and sed to remove the dependencies that I don`t want.

First output this to a file

pip freeze -q -r requirements.txt | sed '/freeze/,$ d' > requirements-froze.txt 

That will output just the libs with version

APScheduler==3.2.0
Eve==0.6.4
Eve-Elastic==0.3.8

Then replace requirements file

mv requirements-froze.txt requirements.txt 

Solution 4:

I still suggest using the official pip freeze > requirements.txt (documentation) compared to the two alternative features using pigar and pipreqs mentioned in the other answers because pip freeze lists the effective package names.

Incomplete comparison among the three as per February 2022

Criteria \ Tool pip freeze > requirements.txt pigar pipreqs
Name mismatch (1) Package my-package==1.0.0 Module my_package == 1.0.0 Module my_package==1.0.0
Module overloading (2) All packages my-package1==1.0.0, my-package2==2.0.0 None Top-level module (version shows 0.0.0) my==0.0.0
Showing only directly used packages No Yes Yes
Minimal contents Yes No Yes

(1) There can be a mismatch between module and package name such as my-package (package name) vs my_package (module name).

(2) There can be several packages using the same top level folder such as my-package1 and my-package2 (package names) which are installed under my/package1 and my/package2, which are imported by Python's command import my.package1 and import my.package2. Note that pipreqs notes version 0.0.0 for the not existing package my.

I know these are very particular cases but I hope giving people this overview can help understanding limitations and avoid possible mistakes.