Sorting package version strings

Interesting less trivial than expected problem (solved): sorting package version numbers:

import re
import rpm

def get_package_version(name):
    """Return version string of installed package."""

    # note: ts can take an argument that is the root of the installation
    #       typically with a var/lib/rpm directory underneath it.
    transaction_set = rpm.ts()

    versions = [header['provideversion'][0]
                for header in transaction_set.dbMatch('name', name)]
    return versions

def version2sortable(version):

    parts = re.split(r'(\d+)', version)
    fields = []
    for part in parts:
            part = int(part)
        except ValueError:
    return tuple(fields)

def cmp_versions(a, b):

    return cmp(version2sortable(a), version2sortable(b))

if __name__ == '__main__':
    print get_package_version('kernel')


['', '', '', '', '']

Note: WordPress is screwing up the markup on the code blocks above. If you have any tips on how to fix this please drop me a line.
Update: Using pre/blockquote hack for now and will try out a code highlighter plug-in when I get the chance. Thanks Tim and Lindsay! :-)

Filed under: fedora,Python — twegener @ 22:04


  1. Tim,



    Comment by timsamoff — 2008-03-07 @ 2:30

  2. I recommend putting your code fragments in a

    . Makes it a lot easier to style your code differently to the rest of the content on your site.

    Syntax highlighting is a bit more difficult, but there are a bunch of WordPress plugins out there that can help you.

    Comment by Lindsay Holmwood — 2008-03-07 @ 6:46

  3. Hah, ok, that didn’t work. What I was trying to say was put them in a <blockquote><pre> combo.

    Comment by Lindsay Holmwood — 2008-03-07 @ 6:48

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress