Produces a canonicalized version string for standard version strings
    in the dotted-numeric-label format.  Function appropriate for use as
    the key function of sort().

    The conversion removes a possible prefix and reformats each key element
    as a long string of digits with leading zeros.  The number of digits
    in each element can be changed with "digits".  The prefix is replaced
    before the result is returned.  Prefixes match the regex '^\w+[_-]'
    where the next character is a digit.

    Non-conforming input is returned with only those completely numeric
    elements reformatted.

def version_sort_key(version, digits=6):
    """
    Produces a canonicalized version string for standard version strings
    in the dotted-numeric-label format.  Function appropriate for use as
    the key function of sort().

    The conversion removes a possible prefix and reformats each key element
    as a long string of digits with leading zeros.  The number of digits
    in each element can be changed with "digits".  The prefix is replaced
    before the result is returned.  Prefixes match the regex '^\w+[_-]'
    where the next character is a digit.

    Non-conforming input is returned with only those completely numeric
    elements reformatted.
"""
    m = re.match('^(\w+[_-])(\d.*)$', version)
    if m:
        prefix = m.group(1)
        version = m.group(2)
    else:
        prefix = ''
    key = []
    for elem in version.split('.'):
        try:
            num = int(elem)
            elem = ('%0'+str(digits)+'d') % num
        except:
            pass
        key.append(elem)
    return prefix + '.'.join(key)