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