2016-07-02 4 views
0

Ich benutze das Pip-Modul in einem Python-Skript, um die Installation von Software/Modulen zu automatisieren. Wie kann ich prüfen, ob die (Remote-) Software/das Modul existiert? Ich habe im pip-Modul nichts gefunden, was das erlaubt.Python3 Pip-Modul, überprüfen, ob Pakete auf PyPi existieren

Mein Code:

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) 

ich überprüfen wollen, ob 'Software' existieren. Danke.

Edit: Ich habe versucht, diesen Code:

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

Aber ich nicht einen Fehler bekommen ...

Antwort

0

Der folgende Code ein Paket (Paket vom Typ 'str') zu importieren versucht. Wenn das Paket nicht importiert werden kann (d. H. Es ist nicht installiert), ruft es Pip auf und versucht, das Paket zu installieren.

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

Dank aber das Testen nicht, wenn das Remote-Paket vorhanden ist, gibt es eine Pythonic Möglichkeit, den Cache der installierbaren Software zugreifen? –

0

Ich würde dies tun:

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! 
    ... 
Verwandte Themen