【问题标题】:How to lookup debian package info with Python如何使用 Python 查找 debian 包信息
【发布时间】:2015-09-17 23:36:03
【问题描述】:

我想使用 python 以编程方式查找 debian 包的最新可用版本。我环顾四周,但找不到合适的关键字来消除所有噪音“python”“parse”“package”“index”碰巧翻了。

有谁知道加载和解析此类包索引的方法吗?
这是一个示例的 URL,我无法用 yaml 或 json 完全解析它: http://packages.osrfoundation.org/gazebo/ubuntu/dists/trusty/main/binary-amd64/ http://packages.osrfoundation.org/gazebo/ubuntu/dists/trusty/main/binary-amd64/Packages

我查看了apt_pkg,但我不知道如何从在线索引中找到我需要的内容。

谢谢!

【问题讨论】:

    标签: python linux ubuntu debian package


    【解决方案1】:

    您可以使用subprocess 模块运行apt-cache policy <app>

    from subprocess import check_output
    
    out = check_output(["apt-cache", "policy","python"])
    print(out)
    

    输出:

    python:
      Installed: 2.7.5-5ubuntu3
      Candidate: 2.7.5-5ubuntu3
      Version table:
     *** 2.7.5-5ubuntu3 0
            500 http://ie.archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages
            100 /var/lib/dpkg/status
    

    您可以通过任何应用程序来获取使用功能的信息:

    from subprocess import check_output,CalledProcessError
    def apt_cache(app):
        try:
            return check_output(["apt-cache", "policy",app])
        except CalledProcessError as e:
            return e.output
    
    print(apt_cache("python"))
    

    或者使用 *args 并运行任何你喜欢的命令:

    from subprocess import check_output,CalledProcessError
    def apt_cache(*args):
        try:
            return check_output(args)
        except CalledProcessError as e:
            return e.output
    
    print(apt_cache("apt-cache","showpkg ","python"))
    

    如果要解析输出,可以使用 re:

    import  re
    from subprocess import check_output,CalledProcessError
    def apt_cache(*args):
        try:
            out = check_output(args)
            m = re.search("Candidate:.*",out)
            return m.group() if m else "No match"
        except CalledProcessError as e:
            return e.output
    
    print(apt_cache("apt-cache","policy","python"))
    Candidate: 2.7.5-5ubuntu3
    

    或获取已安装和候选:

    def apt_cache(*args):
        try:
            out = check_output(args)
            m = re.findall("Candidate:.*|Installed:.*",out)
            return "{}\n{}".format(*m) if m else "No match"
        except CalledProcessError as e:
            return e.output
     print(apt_cache("apt-cache","policy","python"))
    

    输出:

    Installed: 2.7.5-5ubuntu3
    Candidate: 2.7.5-5ubuntu3
    

    【讨论】:

      【解决方案2】:

      没有完全回答问题,但是阅读已安装的 Debian 软件包版本的一种非常优雅的方式

      from pkg_resources import get_distribution
      
      def get_distribution_version(service_name):
          return get_distribution(service_name).version
      

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2011-10-03
        • 2012-11-21
        • 2011-04-15
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多