Pythonic way to check if a package is installed or not

…衆ロ難τιáo~ 提交于 2019-12-23 04:33:42

问题


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

In a bash script, I'd do:

 rpm -qa | grep -w packagename

回答1:


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')
    



回答2:


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")



回答3:


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


来源:https://stackoverflow.com/questions/27833644/pythonic-way-to-check-if-a-package-is-installed-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!