2011-12-08 40 views
8

TLDR;我需要一個簡單的Python調用給定一個包名(例如'make')來查看它是否已經安裝;如果沒有,安裝它(我可以做後者)。確定是否安裝了Yum Python API包?

問題:

因此,有在http://yum.baseurl.org/wiki/YumCodeSnippets給出了幾個代碼示例,但比內IPython的周圍kludging在什麼每個方法的猜測等,似乎沒有要爲任何實際的文件yum的Python API。這顯然是所有的部落知識。

[編輯]顯然我只是偶然發現了API文檔(接收當然可接受的答案,之後)。這不是從主網頁鏈接,但在這裏它是供將來參考:http://yum.baseurl.org/api/yum/

我需要做什麼:

我有依賴於其他系統軟件包部署配置腳本(做,GCC,等等。)。我知道我可以像這樣安裝它們:http://yum.baseurl.org/wiki/YumCodeSnippet/SimplestTransaction但我希望可以選擇查詢它們是否已經安裝,因此如果軟件包不存在,我可以選擇簡單失敗,而不是強制安裝。什麼是正確的電話做這個(或更好的,有人真的很困擾,以正確的文件API代碼示例以外?)

我從來沒有碰過Python之前,這個項目,我真的很喜歡它,但...一些模塊文檔比獨角獸騎士更難以捉摸。

+1

您是否試過了您鏈接的網頁中的'YumSearch'片段? –

+0

是的,但它的結果似乎沒有給我任何安裝狀態的指示 - 只是rpmdb是否知道軟件包(基於指定字段的部分文本匹配)。也許我做錯了。 –

回答

17
import yum 

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

謝謝;我知道這一定很簡單。我理智地檢查了這一點,這一切看起來不錯! –

1

你可以運行「這」的子系統,看看系統是否有您正在尋找的二進制代碼:

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

我這樣做是爲了確定我的產品是否已經安裝(即升級方案),儘管我希望有一種更「純粹」的Python方法。 「哪一種」方法肯定會奏效,但這是一個學習練習,因爲它是一個實用的練習。 :編輯:我不能得到這個正確的格式,但是這是我要做的事 devnull =開放(os.devnull, 「W」) RET = subprocess.call([ 「這」,「MYAPP 「),stdout = devnull,stderr = subprocess.STDOUT,shell = True) devnull.close() #如果」which「找到」myapp「,返回碼爲0(成功)。否則返回1(未找到) –

1

對於任何人誰碰到這個帖子後失蹄,這裏就是我想出了用。請注意,「測試」和「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()