Search code examples
pythoncentosredhat

Pythonic way to check if a package is installed or not


Pythonic way to check list of packages installed in Centos/Redhat?

In a bash script, I'd do:

 rpm -qa | grep -w packagename

Solution

  • import sys
    import rpm
    
    ts = rpm.TransactionSet()
    mi = ts.dbMatch( 'name', sys.argv[1] )
    try :
        h = mi.next()
        print "%s-%s-%s" % (h['name'], h['version'], h['release'])
    except StopIteration:
        print "Package not found"
    
    1. TransactionSet() will open the RPM database
    2. dbMatch with no paramters will set up a match iterator to go over the entire set of installed packages, you can call next on the match iterator to get the next entry, a header object that represents one package
    3. dbMatch can also be used to query specific packages, you need to pass the name of a tag, as well as the value for that tag that you are looking for:

      dbMatch('name','mysql')