Pythonic way to check list of packages installed in Centos/Redhat?
In a bash script, I'd do:
rpm -qa | grep -w packagename
Pythonic way to check list of packages installed in Centos/Redhat?
In a bash script, I'd do:
rpm -qa | grep -w packagename
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"
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')
you can use Subprocess:
import subprocess
child = subprocess.Popen("rpm -qa | grep -w packagename", stdout=subprocess.PIPE, shell=True)
output = child.communicate()[0]
print output
using os:
import os
os.system("rpm -qa | grep -w packagename")
import os
present=0
notpresent=0
f3=open('INSTALLED.log','w')
f2=open('NOTINSTALLED.log','w')
f1=open('installed_packagelist.log','w')
var = os.popen("rpm -qa --queryformat '[%{NAME}\n]'").read()
f1.write(var)
lines = [line.rstrip('\n') for line in open('installed_packagelist.log')]
for index in range(len(lines)):
contents = lines[index]
test_str = "rpm -V " + contents
var = os.system(test_str)
if (var == 0):
print contents + "file present"
present = present +1
f3.write(contents)
else:
print contents + "file not present"
notpresent = notpresent + 1
f2.write(contents)
print present
print notpresent
f2.close()
f3.close()
f3=open('INSTALLED.log','r')
f2=open('NOTINSTALLED.log','r')
data=f3.read()
print data
print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
data=f2.read()
print data
I could not get this answer: https://stackoverflow.com/a/51258124/498657 to work on Python 3.6.8, what did work for me was:
import sys
import rpm
ts = rpm.TransactionSet()
mi = ts.dbMatch( 'name', 'lsof' )
rpmhit=0
for h in mi:
if h['name'] == 'lsof':
rpmhit=1
break
if rpmhit == 0:
print('Error: Package lsof not installed. Install using: dnf install lsof')
sys.exit(3)
For Python 3.6.12 to verify if package "pacemaker-cli" is installed I used:
import rpm
ts = rpm.TransactionSet()
mi = ts.dbMatch( 'name', 'pacemaker-cli' )
try :
h = mi.__next__()
print ("%s-%s-%s.%s" % (h['name'].decode(), h['version'].decode(), h['release'].decode(), h['arch'].decode()))
except StopIteration:
print ("Package not found")