Product SiteDocumentation Site

16.3.4. Querying for specific packages

When you call dbMatch on a transaction set object, passing no parameters means to iterate over the entire set of installed packages in the RPM database. You can also query for specific packages using dbMatch. To do so, you need to pass the name of a tag in the header, as well as the value for that tag that you are looking for. The basic syntax follows:
mi = ts.dbMatch(tag_name, value)
For example, to query for all packages named sendmail, use code like the following:
mi = ts.dbMatch('name', 'sendmail')
The call to dbMatch returns an rpmdbMatchIterator. You can query on any of the tags in the header, but by far the most common query is by name.
Note
Some matches are fast and some are much slower. If you try to match on a tag that is indexed in the RPM database, the matches will perform much faster than for those tags that are not indexes. To determine which tags are indexed, look at the files in /var/lib/rpm. For example, Name and Requirename are files in /var/lib/rpm. These tags are indexed and will therefore match quickly.
Listing 17-2 shows an example Python script which queries for a particular package name and then prints out the name, version, and release for all matching packages.
Listing 17-2: rpmq.py
#!/usr/bin/python
# Acts like rpm -q and lists the N-V-R for installed
# packages that match a given name.
# Usage:
# python rpmq.py package_name
import rpm, sys
ts = rpm.TransactionSet()
mi = ts.dbMatch( 'name', sys.argv[1] )
for h in mi:
print "%s-%s-%s" % (h['name'], h['version'], h['release'])
When you call this script, you need to pass the name of a package to query, which the python interpreter will store in sys,argv[1] in the call to dbMatch. For example:
$ python rpmq.py sendmail
sendmail-8.12.5-7