Pythonic way to check if a package is installed or not

前端 未结 4 1760
小鲜肉
小鲜肉 2020-12-20 00:46

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

In a bash script, I\'d do:

 rpm -qa | grep -w packagename
相关标签:
4条回答
  • 2020-12-20 01:06
    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
    
    0 讨论(0)
  • 2020-12-20 01:08

    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")
    
    0 讨论(0)
  • 2020-12-20 01:12
    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')
      
    0 讨论(0)
  • 2020-12-20 01:19

    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)
    
    0 讨论(0)
提交回复
热议问题