How to get list installed Linux rpms with Python?

别等时光非礼了梦想. 提交于 2019-12-24 15:32:22

问题


I use subprocess.getoutput("rpm -qa").split("\n"),it's not very well. rpmfile module can only read .rpm files

Can you help me find one module?


回答1:


If you are using Fedora, there is a module called rpm from the package rpm-python that will allow you to query the rpm database:

import rpm

ts = rpm.TransactionSet()
mi = ts.dbMatch()
for h in mi:
    print "%s-%s-%s" % (h['name'], h['version'], h['release'])

That is a simple piece of code from the documentation. See here for more information.




回答2:


I modified code similar to what is posted by Marcus Poli. This was tested using Python 2.7 and 3.6 on CentOS 7.4. My original question was How do I check if an rpm package is installed using Python?

import os
rpm = 'binutils'
f = os.popen('rpm -qa')
arq = f.readlines()
for r in arq:
   if rpm in r:
      print("{} is installed".format(r.rstrip()))

Output:

binutils-devel-2.27-34.base.el7.x86_64 is installed
binutils-2.27-34.base.el7.x86_64 is installed



回答3:


Maybe code below is useful for someone.

import os
f = os.popen('rpm -qa')
arq = f.readlines()
#print("First file=" + arq[0].strip())
for x in arq:
    print(x) 


来源:https://stackoverflow.com/questions/34360353/how-to-get-list-installed-linux-rpms-with-python

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