Search code examples
pythondebianapt

How to compare Debian package versions?


I looked at python-apt and python-debian, and they don't seem to have functionality to compare package versions. Do I have to write my own, or is there something I can use?

Ideally, it would look something like:

>>> v1 = apt.version("1:1.3.10-0.3")
>>> v2 = apt.version("1.3.4-1")
>>> v1 > v2
True

Solution

  • You could use apt_pkg.version_compare:

    import apt_pkg
    apt_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 that for newer versions: apt.VersionCompare is now apt_pkg.version_compare.