排序应用程序版本号

时间:2013-02-21 12:20:51

标签: python

我是初学者。我想编写一个脚本来清理其文件夹中的旧版Google Chrome应用程序版本,我想知道如何以有效的方式“排序”应用程序版本号。最好的方法是什么?

这是我的“春季大扫除”剧本:

import os
import sys
import re
import operator
import shutil


GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY=r'C:\Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\Application'

REGEX_GOOGLE_CHROME_APPLICATION_VERSION = '^(\d+)\.(\d+)\.(\d+)\.(\d+)$'


def sorted_by_version_number(versions_list):
  version_elements = len(versions_list[0])
  for index in range(version_elements-1, 0, -1):
    key = operator.itemgetter(index)
    versions_list.sort(key=key, reverse = True)
  return versions_list


def delete_old_google_chrome_versions():
  REGEX = re.compile(REGEX_GOOGLE_CHROME_APPLICATION_VERSION)
  application_versions = []
  for filename in os.listdir(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY):
    filepath = os.path.join(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY,
                            filename)
    if os.path.isdir(filepath):
      match = REGEX.match(filename)
      if match:
        version = (v1, v2, v3, v4) = [int(match.group(i)) for i in range(1, 5)]
        application_versions.append(version)
  versions_to_delete = sorted_by_version_number(application_versions)[1:]
  for application_version in versions_to_delete:
    directory_name = '.'.join([str(v) for v in application_version])
    directory_path = os.path.join(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY,
                                  directory_name)
    print('Deleting Google Chrome application directory: {}...'.format(
      directory_path))
    # shutil.rmtree(directory_path)


def main():
  delete_old_google_chrome_versions()


if __name__ == '__main__':
  main()

或者,如何改进此脚本?任何建议都会有所帮助,因为我在Python中真的没用。

1 个答案:

答案 0 :(得分:0)

我对这个问题的回答直接转换为Python:

How to compare software version number using js? (only number)

您可以使用此比较算法对列表进行排序。