Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare requirement file and actually installed Python modules?

Given requirements.txt and a virtualenv environment, what is the best way to check from a script whether requirements are met and possibly provide details in case of mismatch?

Pip changes it's internal API with major releases, so I seen advices not to use it's parse_requirements method.

There is a way of pkg_resources.require(dependencies), but then how to parse requirements file with all it's fanciness, like github links, etc.?

This should be something pretty simple, but can't find any pointers.

UPDATE: programmatic solution is needed.

like image 467
Roman Susi Avatar asked Aug 19 '16 19:08

Roman Susi


1 Answers

You can save your virtualenv's current installed packages with pip freeze to a file, say current.txt

pip freeze > current.txt

Then you can compare this to requirements.txt with difflib using a script like this:

import difflib

req = open('requirements.txt')
current = open('current.txt')

diff = difflib.ndiff(req.readlines(), current.readlines())
delta = ''.join([x for x in diff if x.startswith('-')])

print(delta)

This should display only the packages that are in 'requirements.txt' that aren't in 'current.txt'.

like image 64
mohrtw Avatar answered Oct 12 '22 11:10

mohrtw