Product SiteDocumentation Site

16.4. Reading Package Files

As you would expect, the Python API includes methods for working with RPM package files in addition to installed RPM packages. Most of these methods require a header object, which you can read from an RPM package file.

16.4.1. Reading headers from package files

Like the C function rpmReadPackageFile, the Python API provides a convenient way to read in a header object from an RPM package file. The hdrFromFdno method reads an RPM header from an open file descriptor. The basic syntax is:
h = ts.hdrFromFdno(fdno)
Note
The hdrFromFdno method uses Python’s low-level file descriptors instead of the higher-level Python file objects. In the RPM C library, an FD_t is a FILE**. This could be bound to a Python class, but that is outside the scope of this chapter.
The following example shows a function that opens a file, reads in the RPM header, and then closes the file:
def readRpmHeader(ts, filename):
""" Read an rpm header. """
fd = os.open(filename, os.O_RDONLY)
h = ts.hdrFromFdno(fd)
os.close(fd)
return h
ts = rpm.TransactionSet()
h = readRpmHeader( ts, 'n-r-v.rpm' )
The hdrFromFdno method raises a number of exceptions based on issues detected with the package files. The following example shows these exceptions:
def readRpmHeader(ts, filename):
""" Read an rpm header. """
fd = os.open(filename, os.O_RDONLY)
h = None
tryL
h = ts.hdrFromFdno(fd)
except rpm.error, e:
if str(e) == "public key not available":
print str(e)
if str(e) == "public key not trusted":
print str(e)
if str(e) == "error reading package header":
print str(e)
h = None
os.close(fd)
return h
ts = rpm.TransactionSet()
h = readRpmHeader( ts, 'n-r-v.rpm' )
You can decide in your code whether the exceptions should stop processing or not.