关于Python中的rpm模块

3 投票
2 回答
5052 浏览
提问于 2025-04-17 13:21

我查了一些资料,发现rpm模块只能用来查找已经安装的rpm包的信息。我想用Python的rpm模块来搜索文件夹里的*.rpm文件,并了解它们的一些信息,比如发布版本或版本号。请问用rpm模块能做到这一点吗?

2 个回答

0

我不知道有什么办法可以做到这一点。最简单的办法就是直接调用rpm命令,然后解析一下数据。

subprocess.check_output( ["rpm", "-qip", "CentOS_Image/Packages/python-2.6.6-29.el6_2.2.x86_64.rpm" ] )

'Name        : python\nVersion     : 2.6.6\nRelease     : 29.el6_2.2\nArchitecture: x86_64\nInstall Date: (not installed)\nGroup       : Development/Languages\nSize        : 21290059\nLicense     : Python\nSignature   : RSA/SHA1, Mon 18 Jun 2012 14:47:20 BST, Key ID 0946fca2c105b9de\nSource RPM  : python-2.6.6-29.el6_2.2.src.rpm\nBuild Date  : Mon 18 Jun 2012 14:21:55 BST\nBuild Host  : c6b5.bsys.dev.centos.org\nRelocations : (not relocatable)\nPackager    : CentOS BuildSystem <http://bugs.centos.org>\nVendor      : CentOS\nURL         : http://www.python.org/\nSummary     : An interpreted, interactive, object-oriented programming language\nDescription :\nPython is an interpreted, interactive, object-oriented programming\nlanguage often compared to Tcl, Perl, Scheme or Java. Python includes\nmodules, classes, exceptions, very high level dynamic data types and\ndynamic typing. Python supports interfaces to many system calls and\nlibraries, as well as to various windowing systems (X11, Motif, Tk,\nMac and MFC).\n\nProgrammers can write new built-in modules for Python in C or C++.\nPython can be used as an extension language for applications that need\na programmable interface. This package contains most of the standard\nPython modules, as well as modules for interfacing to the Tix widget\nset for Tk and RPM.\n\nNote that documentation for Python is provided in the python-docs\npackage.\n'
6

如果有人在寻找答案时来到这里,这里有一种使用python-rpm的方法:

import os
import rpm

fdno = os.open(PATH_TO_RPM_FILE, os.O_RDONLY)
ts = rpm.ts()
hdr = ts.hdrFromFdno(fdno)
os.close(fdno)

(注意调用了os.close())

现在,hdr中保存了RPM的头部信息。你可以像访问字典一样,用RPMTAG_*的值作为键来获取各个属性,比如:

arch = hdr[rpm.RPMTAG_ARCH]

你可以尝试使用dir()来反向工程所有可能的RPMTAG_*值:

import rpm
print '\n'.join(filter(lambda x: x.startswith('RPMTAG'), dir(rpm)))

你也可以在hdr上调用keys(),但它会返回可能的键,都是整数,这样可能不太友好。

我发现,使用python-rpm而不是通过命令行工具作为子进程来处理大量RPM文件时,性能提升显著。

想了解更多信息,可以查看http://rpm5.org/docs/api/classRpmhdr.html

撰写回答