Version 5 (modified by james, 9 years ago)
add #!python

Yum Code Snippets

This is just snippets of code using the yum modules for common/simple tasks. Add/edit/comment as you'd like. All of these snippets assume that you have done "import yum, os, sys".

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

my = yum.YumBase()
my.install(name='somepackage')
my.remove(name='someotherpackage')
my.resolveDeps()
my.processTransaction()

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 ./thisfile.py url://to/my/repo

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

my.repos.disableRepo('*')

newrepo = yum.yumRepo.YumRepository('myrepo')
newrepo.name = 'myrepo - %s' % url
newrepo.baseurl = [url] 
newrepo.basecachedir = my.conf.basecachedir
newrepo.enablegroups = True
my.repos.add(newrepo)
my.repos.enableRepo(newrepo.id)
my.doRepoSetup(thisrepo=newrepo.id)

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

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

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

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

more?