Version 3 (modified by james, 10 years ago)
add yum list snippet

Yum Code Snippets

This is just snippets of code using the yum modules for common/simple tasks. Add/edit/comment as you'd like.

Open a local package as a yum package object w/o all the rest of the yum stuff:

import yum.packages
import rpmUtils.transaction
ts = rpmUtils.transaction.initReadOnlyTransaction()
lp = yum.packages.YumLocalPackage(ts, '/home/skvidal/yum-3.2.8-1.noarch.rpm')

replace '/home/skvidal/yum-3.2.8-1.noarch.rpm' with the full path to the package

Return the gpg signature info from a package:

import yum.packages
import rpmUtils.transaction
from rpmUtils.miscutils import getSigInfo
ts = rpmUtils.transaction.initReadOnlyTransaction()
lp = yum.packages.YumLocalPackage(ts, '/home/skvidal/yum-3.2.8-1.noarch.rpm')

print getSigInfo(lp.hdr)

Given a filename of an rpm parse out the major information that's available:

from rpmUtils.miscutils import splitFilename

myfn = 'a2ps-4.13b-57.1.el5.src.rpm'

(name, ver, rel, epoch, arch) = splitFilename(myfn)

Simplest transaction you can have (yum 3.2.7 and above):

import yum
my = yum.YumBase()

This helps you setup a repo at an arbitrary location, as a user and play with the object. Paste this into a file then run it with ipython for maximum usefulness like:

ipython ./ url://to/my/repo

import yum, os, sys
my = yum.YumBase()
my.conf.basecachedir = '/tmp/whereever'
if not os.path.exists(my.conf.basecachedir):
my.conf.cache = 0
url = sys.argv[1] 


newrepo = yum.yumRepo.YumRepository('myrepo') = 'myrepo - %s' % url
newrepo.baseurl = [url] 
newrepo.basecachedir = my.conf.basecachedir
newrepo.enablegroups = True

Search for which package(s) own a file on the system

import yum
my = yum.YumBase()
pkgs = my.rpmdb.whatProvides('/boot/vmlinuz-', None, (None, None,None))
for pkg in pkgs:
print pkg

Report back the list of issues with an installed package (like rpm -V pkgname):

import yum
my = yum.YumBase()
pkgs = my.rpmdb.searchNevra(name='yum')
for pkg in pkgs:
    errors = pkg.verify()
    for fn in errors.keys():
        for prob in errors[fn]:
            print '%s - %s' % (fn, prob.message)

A simple version of the "yum list" command:

yb = yum.YumBase()
yb.conf.cache = os.geteuid() != 1
pl = yb.doPackageLists(patterns=sys.argv[1:])
if pl.installed:
    print "Installed Packages"
    for pkg in sorted(pl.installed):
        print pkg
if pl.available:
    print "Available Packages"
    for pkg in sorted(pl.available):
        print pkg, pkg.repo
if pl.reinstall_available:
    print "Re-install Available Packages"
    for pkg in sorted(pl.reinstall_available):
        print pkg, pkg.repo