How to compare Debian package versions? How to compare Debian package versions? python python

How to compare Debian package versions?


Perhaps because the title doesn't mention Python (though the tags do), Google brought me here when asking the same question but hoping for a bash answer. That seems to be:

$ dpkg --compare-versions 11a lt 100a && echo truetrue$ dpkg --compare-versions 11a gt 100a && echo true$ 

To install a version of rubygems that's at least as new as the version from lenny-backports in a way that gives no errors on lenny and squeeze installations:

sudo apt-get install rubygems &&VERSION=`dpkg-query --show --showformat '${Version}' rubygems` &&dpkg --compare-versions $VERSION lt 1.3.4-1~bpo50+1 &&sudo apt-get install -t lenny-backports rubygems

Perhaps I should have asked how to do that in a separate question, in the hope of getting a less clunky answer.


You could use apt_pkg.version_compare:

import apt_pkgapt_pkg.init_system()a = '1:1.3.10-0.3'b = '1.3.4-1'vc = apt_pkg.version_compare(a,b)if vc > 0:    print('version a > version b')elif vc == 0:    print('version a == version b')elif vc < 0:    print('version a < version b')        

yields

version a > version b

Thanks to Tshepang for noting in the comments thatfor newer versions: apt.VersionCompare is now apt_pkg.version_compare.


python-debian can do this too. It's used in an almost identical way to python-apt:

from debian import debian_support a = '1:1.3.10-0.3'b = '1.3.4-1'vc = debian_support.version_compare(a,b)if vc > 0:    print('version a > version b')elif vc == 0:    print('version a == version b')elif vc < 0:    print('version a < version b')

ouput:

version a > version b