确定包是否与Yum Python API一起安装?

2024-06-28 11:57:19 发布

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

TLDR;我需要一个简单的Python调用,给定一个包名(例如“make”)来查看它是否已安装;如果没有,请安装它(我可以完成后一部分)。

问题:

所以在http://yum.baseurl.org/wiki/YumCodeSnippets中给出了一些代码示例,但是除了在ipython内部胡思乱想并猜测每个方法的作用之外,似乎没有任何针对Python API for yum的实际文档。显然都是部落知识。

[编辑]显然,我只是意外地发现了API文档(当然,在收到可接受的答案之后)。它不是从主页链接的,但这里是供将来参考的:http://yum.baseurl.org/api/yum/

我需要做的:

我有一个依赖于其他系统包(make、gcc等)的部署配置脚本。我知道我可以这样安装它们:http://yum.baseurl.org/wiki/YumCodeSnippet/SimplestTransaction,但我希望在安装之前可以查询它们是否已经安装,因此如果没有软件包,我可以选择直接失败,而不是强制安装。要做到这一点,正确的调用是什么(或者更好,是否有人真的费心在代码示例之外正确地编写API文档?)

在这个项目之前我从未接触过Python,我真的很喜欢它,但是。。。一些模块文档比骑独角兽的小妖精更难以捉摸。


Tags: 方法代码文档orgapihttp示例for
3条回答

您可以在子系统上运行“which”,查看系统是否具有您要查找的二进制文件:

import os
os.system("which gcc")
os.system("which obscurepackagenotgoingtobefound")

对于后来偶然发现这篇文章的人,以下是我的想法。注意,“testing”和“skip_install”是我从脚本调用中解析的标志。

    print "Checking for prerequisites (Apache, PHP + PHP development, autoconf, make, gcc)"
    prereqs = list("httpd", "php", "php-devel", "autoconf", "make", "gcc")

    missing_packages = set()
    for package in prereqs:
        print "Checking for {0}... ".format([package]),

        # Search the RPM database to check if the package is installed
        res = yb.rpmdb.searchNevra(name=package)
        if res:
            for pkg in res:
                print pkg, "installed!"
        else:
            missing_packages.add(package)
            print package, "not installed!"
            # Install the package if missing
            if not skip_install:
                if testing:
                    print "TEST- mock install ", package
                else:
                    try:
                        yb.install(name=package)
                    except yum.Errors.InstallError, err:
                        print >> sys.stderr, "Failed during install of {0} package!".format(package)
                        print >> sys.stderr, str(err)
                        sys.exit(1)

    # Done processing all package requirements, resolve dependencies and finalize transaction
    if len(missing_packages) > 0:
        if skip_install:
            # Package not installed and set to not install, so fail
            print >> sys.stderr, "Please install the {0} packages and try again.".format(
                ",".join(str(name) for name in missing_packages))
            sys.exit(1)
        else:
            if testing:
                print "TEST- mock resolve deps and process transaction"
            else:
                yb.resolveDeps()
                yb.processTransaction()
import yum

yb = yum.YumBase()
if yb.rpmdb.searchNevra(name='make'):
   print "installed"
else:
   print "not installed"

相关问题 更多 >