2016-07-02 128 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! 
    ...