2016-07-02 49 views
0

我在python腳本中使用pip模塊來自動安裝軟件/模塊。我該如何檢查(遠程)軟件/模塊是否存在?我沒有發現任何可以做到這一點的pip模塊。Python3 pip模塊,檢查軟件包是否存在PyPi

我的代碼:

class install_pip: 
    def __init__(self): 
     self._liste=['install'] 
    def install(self): 
     pip.main(self._liste) 
    def addsoftware(self, software): 
     if type(software) is str: 
      self._liste.append(software) 
     if type(software) is list: 
      for i in software: 
       self._liste.append(i) 
    def delsoftware(self, software): 
     if type(software) is str: 
      self._liste.remove(software) 
     if type(software) is list: 
      for i in software: 
       self._liste.remove(i) 
    def _return(self): 
     return self._liste[1:len(self._liste)] 
    list = property(_return) 

我要檢查,如果 '軟件' 存在。 謝謝。

編輯:我想這個代碼:

try: 
    pip.main(['install', 'nonexistentpackage']) 
except pip.InstallationError as err: 
    print(echec) 

但我沒有得到任何錯誤...

回答

0

下面的代碼將嘗試導入一個包(包類型「STR」的)。如果它無法導入包(即未安裝),它將調用Pip並嘗試安裝該包。

import pip 

def import_or_install(package): 
    try: 
     __import__(package) 
     print (package, "exists, and was successfully imported.") 
    except ImportError: 
     pip.main(['install', package]) 

import_or_install("name of package") 
+0

謝謝,但如果遠程包存在,有沒有訪問的安裝軟件的緩存Python化的方式,不考? –

0

我這樣做:

import requests 
response = requests.get("http://pypi.python.org/pypi/{}/json" 
         .format(module_name)) 
if response.status_code == 200: 
    # OK, the json document exists so you can 
    # parse the module details if you want 
    # by using data = response.json() 
    # 
    # anyway, here you know that the module exists! 
    ...