0

我一直在使用 apt_pkg 和 apt 库的组合从每个包中获取以下详细信息:

package.name
package.installedVersion
package.description
package.homepage
package.priority

我能够通过以下方式获得我需要的东西,我不完全确定这是获得结果的最佳方法:

import apt_pkg, apt

apt_pkg.InitConfig()
apt_pkg.InitSystem()

aptpkg_cache = apt_pkg.GetCache() #Low level 
apt_cache = apt.Cache() #High level

apt_cache.update()
apt_cache.open()

pkgs = {}
list_pkgs = []

for package in aptpkg_cache.Packages:
       try:
          #I use this to pass in the pkg name from the apt_pkg.packages
          #to the high level apt_cache which allows me to obtain the
          #details I need. Is it better to just stick to one library here?
          #In other words, can I obtain this with just apt_pkg instead of using apt?

          selected_package = apt_cache[package.name]

          #Verify that the package can be upgraded
          if check_pkg_status(package) == "upgradable":
           pkgs["name"] = selected_package.name
               pkgs["version"] = selected_package.installedVersion
               pkgs["desc"] = selected_package.description
               pkgs["homepage"] = selected_package.homepage
               pkgs["severity"] = selected_package.prority

               list_pkgs.append(pkgs)
          else:
               print "Package: " + package.name + " does not exist"
               pass #Not upgradable?

        except:
          pass #This is one of the main reasons why I want to try a different method.
              #I'm using this Try/Catch because there are a lot of times that when
              #I pass in package.name to apt_cache[], I get error that package does not
              #exists... 


def check_pkg_status(package):
        versions = package.VersionList
        version = versions[0]
        for other_version in versions:
            if apt_pkg.VersionCompare(version.VerStr, other_version.VerStr)<0:
                version = other_version

        if package.CurrentVer:
            current = package.CurrentVer
            if apt_pkg.VersionCompare(current.VerStr, version.VerStr)<0:
                return "upgradable"
            else:
                return "current"
        else:
            return "uninstalled"

我想找到一种使用 apt_pkg/apt 来获取每个可能升级/更新候选包的详细信息的好方法?

我目前这样做的方式是,我只获得系统中已有软件包的更新/升级,即使我注意到 Debian 的更新管理器向我显示了我系统中没有的软件包。

4

1 回答 1

3

以下脚本基于您的 python 代码,适用于我的 Ubuntu 12.04,也适用于任何具有 python-apt 0.8+ 的系统

import apt

apt_cache = apt.Cache() #High level

apt_cache.update()
apt_cache.open()

list_pkgs = []

for package_name in apt_cache.keys():
    selected_package = apt_cache[package_name]

    #Verify that the package can be upgraded
    if selected_package.isUpgradable:
        pkg = dict(
            name=selected_package.name,
            version= selected_package.installedVersion,
            desc= selected_package.description,
            homepage= selected_package.homepage,
            severity= selected_package.priority)
        list_pkgs.append(pkg)

print list_pkgs
于 2013-01-08T12:18:54.503 回答