Nvasion Nvasion - 6 days ago 6
Linux Question

Python show all installed packages

Is there a way for python to show all apt/yum packages installed on a server? I have a program that can only grab one package that I specify but I'd like to know if there is a apt-show-versions/yum check-update like module in python since python-yum and python-apt only do single packages.

Thanks.

EDIT:

Here is the code I have currently:

# For finding the package version and using the package name -i
def aptpkg(package_name):
cache = apt.Cache()
pkg = cache[package_name]
host = subprocess.Popen('hostname', stdout=subprocess.PIPE, universal_newlines=True).stdout.read().strip()
if pkg.is_installed:
print host
print 'Current ' + package_name + ' installed:', pkg.installed.version
con.execute("insert into ansible_packagelist(date, host, package_name, installed_version) values (current_timestamp,%s,%s,%s)", (host, package_name, pkg.installed.version,))
else:
print host, package_name + ' is not installed on this system.\n'
if pkg.is_upgradable:
print 'Upgradeable version of ' + package_name + ' :', pkg.candidate.version
con.execute("update ansible_packagelist set upgradeable_version = %s where package_name = %s", (pkg.candidate.version, package_name))
db.commit()

Answer

This is the pythonic way:

import apt
cache = apt.Cache()

for mypkg in apt.Cache():
    if cache[mypkg.name].is_installed:
        print mypkg.name

For yum, I need first to login to RH/Centos system. But you can have a look to the yum library and you'll find something like 'rpmdb.searchNevra'

Comments