9

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

问题:

因此,在http://yum.baseurl.org/wiki/YumCodeSnippets中给出了一些代码示例,但除了在 ipython 中四处游荡并猜测每种方法的作用之外,似乎没有任何实际的文档百胜的 Python API。这显然是所有部落知识。

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

我需要做什么:

我有一个依赖于其他系统包(make、gcc 等)的部署配置脚本。我知道我可以像这样安装它们:http: //yum.baseurl.org/wiki/YumCodeSnippet/SimplestTransaction但我想在这样做之前可以选择查询它们是否已经安装,所以我可以拥有如果软件包不存在而不是强制安装,则简单地失败的附加选项。这样做的正确调用是什么(或者更好的是,有没有人真的费心在代码示例之外正确记录 API?)

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

4

4 回答 4

19
import yum

yb = yum.YumBase()
if yb.rpmdb.searchNevra(name='make'):
   print "installed"
else:
   print "not installed"
于 2011-12-09T20:40:11.420 回答
2

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

import os
os.system("which gcc")
os.system("which obscurepackagenotgoingtobefound")
于 2011-12-09T17:58:56.380 回答
1

对于以后偶然发现这篇文章的任何人,这就是我想出的。请注意,“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()
于 2011-12-09T23:57:17.620 回答
0
import yum

yb = yum.YumBase()
yb.isPackageInstalled('make')
于 2018-11-05T22:13:01.197 回答