我想使用 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/