ruffsl
ruffsl

Reputation: 1513

How to lookup debian package info with Python

I'd like to look up the latest available version of a debian package programmatically using python. I've looked around, but can't find the right keywords to cut through all of the noise "python" "parse" "package" "index" happens to turn over.

Does anyone know of a way to load and parse such a package index?
Here is a URL to a sample, I can't quite parse it with yaml or json: http://packages.osrfoundation.org/gazebo/ubuntu/dists/trusty/main/binary-amd64/ http://packages.osrfoundation.org/gazebo/ubuntu/dists/trusty/main/binary-amd64/Packages

I've looked at apt_pkg, but I'm not sure how to work it to what I need from the online index.

Thanks!

Upvotes: 2

Views: 1655

Answers (2)

Reto Tschuppert
Reto Tschuppert

Reputation: 11

Not fully answering the question but a very elegant way to read the installed Debian package version

from pkg_resources import get_distribution

def get_distribution_version(service_name):
    return get_distribution(service_name).version

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You can use the subprocess module to run apt-cache policy <app>:

from subprocess import check_output

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

Output:

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

You can pass whatever app you are trying to get the info for using a fucntion:

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"))

Or use *args and run whatever command you like:

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"))

If you want to parse the output you can use 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

Or to get the installed and candidate:

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"))

Output:

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

Upvotes: 2

Related Questions