python - 如何使用Python查找debian软件包信息

标签 python linux ubuntu debian package

我想使用 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 ,但我不确定如何将其处理为我需要的在线索引。

谢谢!

最佳答案

您可以使用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

关于python - 如何使用Python查找debian软件包信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150697/

相关文章:

php - 来自 PHP 的带有 SFTP 的 shell 脚本

python - 为什么 .bind() 方法不能与 Tkinter 中的框架小部件一起使用?

python - 匹配python中的特定字符串+任意 float

linux - 如何使fzf发送与标准输出不匹配的文本?

linux - FTP Shell 脚本不起作用

linux - 更新到 Ubuntu 18.04 后无法使用大多数 Python 应用

python - 为什么 5^(4-4) + 9 和 (5^(4-4)) + 9 的结果不同?

Raspberry Pi 的 Python 脚本无法正常运行

php - Apache2返回php源码

linux - Ubuntu set -g 无法更改 tmux 中的滚动行为 - 设置 postgres