Python显示所有已安装的包

2024-05-17 16:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

python有没有办法显示服务器上安装的所有apt/yum包?我有一个程序只能获取我指定的一个包,但是我想知道python中是否有apt show versions/yum check update-like模块,因为python-yum和python-apt只做单个包。

谢谢。

编辑:

这是我目前的代码:

# For finding the package version and using the package name -i
def aptpkg(package_name):
    cache = apt.Cache()
    pkg = cache[package_name]
    host = subprocess.Popen('hostname', stdout=subprocess.PIPE, universal_newlines=True).stdout.read().strip()
    if pkg.is_installed:
        print host
        print 'Current ' + package_name + ' installed:', pkg.installed.version
        con.execute("insert into ansible_packagelist(date, host, package_name, installed_version) values (current_timestamp,%s,%s,%s)", (host, package_name, pkg.installed.version,))
    else:
        print host, package_name + ' is not installed on this system.\n'
    if pkg.is_upgradable:
        print 'Upgradeable version of ' + package_name + ' :', pkg.candidate.version
        con.execute("update ansible_packagelist set upgradeable_version = %s where package_name = %s", (pkg.candidate.version, package_name))
    db.commit()

Tags: installedthenamehostpackagecacheisversion
3条回答

maxadamo的答案是正确的,但是Cache初始化了两次,我不知道为什么。

相反,您只能实例化一个缓存,循环它并直接在for循环中访问pkg。您不需要额外的查找,因为您已经可以访问pkg的属性。

所以这里有一个更像Python的方法:

import apt
cache = apt.Cache()

for pkg in cache:
    if pkg.is_installed:
        print pkg.name

使用subprocess运行shell命令。

from subprocess import call

对于apt:call(["dpkg", "-l"])

对于yum:call(["yum list installed"])

这是Python的方式:

import apt
cache = apt.Cache()

for mypkg in apt.Cache():
    if cache[mypkg.name].is_installed:
        print mypkg.name

对于yum,我需要首先登录到RH/Centos系统。 但是你可以去yum库看看,你会发现类似“rpmdb.searchNevra”的东西

相关问题 更多 >