Product SiteDocumentation Site

Refining queries

The pattern method on a match iterator allows you to refine a query. This narrows an existing iterator to only show the packages you desire. The basic syntax follows:
mi.pattern(tag_name, mode, pattern)
The two main uses of the pattern method are to query on more than one tag, such as the version and name, or to narrow the results of a query, using the rich set of pattern modes. The mode parameter names the type of pattern used, which can be one of those listed in Table 17-2.
Table 17-2 Pattern modes for the pattern method
Type
Meaning
rpm.RPMMIRE_DEFAULT
Same as regular expressions, but with \., .*, and ^..$ added
rpm.RPMMIRE_GLOB
Glob-style patterns using fnmatch
rpm.RPMMIRE_REGEX
Regular expressions using regcomp
rpm.RPMMIRE_STRCMP
String comparisons using strcmp
Cross Reference
For more on these patterns, see the online manual pages for fnmatch(3), glob(7), regcomp(3), regex(7), and strcmp(3). The pattern method calls rpmdbSetIteratorRE from the C API, covered in the “Database Iterators” section in Chapter 15, Programming RPM with C .
To query for all packages starting with py, for example, you can use code like the following:
import rpm
ts = rpm.TransactionSet()
mi = ts.dbMatch()
mi.pattern('name', rpm.RPMMIRE_GLOB, 'py*' )
for h in mi:
    # Do something with the header...
    pass
Listing 17-4 shows an example for glob-based querying.
Listing 17-4: rpmglob.py
#!/usr/bin/python
# Acts like rpm -q and lists the N-V-R for installed packages
# that match a given name using a glob-like syntax
#
# Usage:
# python rpmglob.py "package_fragment*"

import sys

import rpm

ts = rpm.TransactionSet()
mi = ts.dbMatch()
if not mi:
    print "No packages found."
else:
    mi.pattern('name', rpm.RPMMIRE_GLOB, sys.argv[1] )
    for h in mi:
        print "%s-%s-%s" % (h['name'], h['version'], h['release'])
When you run this script, you’ll see output like the following:
$ python rpmglob.py "py*"
pyxf86config-0.3.1-2
python-devel-2.2.1-17
pygtk2-devel-1.99.12-7
pygtk2-libglade-1.99.12-7
pygtk2-1.99.12-7
pyOpenSSL-0.5.0.91-1
python-optik-1.3-2
python-docs-2.2.1-17
python-2.2.1-17
python-tools-2.2.1-17
In addition to working with the RPM database, the Python API also provides access to RPM files.