Wie kann ich „Modul nicht gefunden“ von „Modul warf Ausnahme“ auf Import unterscheiden?

StackOverflow https://stackoverflow.com/questions/1860363

  •  13-09-2019
  •  | 
  •  

Frage

In Python import does_not_exist wirft ImportError und

import exists

exists.py:

import does_not_exist

wird auch ImportError erhöhen.

Wie soll ich sagen, den Unterschied im Code?

War es hilfreich?

Lösung

Die einzige Methode, die ich weiß, ist, wenn die Top-Level-Modulname zu überprüfen ist, Nachricht in die Ausnahme der „existiert“ ist oder nicht:

try:
  import exists
except ImportError as exc:
  if "exists" in str(exc):
     pass
  else:
     raise

Könnte dies ein Feature-Request für Import Python sein? eine Variable für die Modulnamen zu haben sicherlich bequem sein würde ..

Andere Tipps

Sie können die tb_next des Zurückverfolgungs verwenden. Es wird aus Nichts anders sein, wenn die Ausnahme auf ein anderes Modul aufgetreten

import sys
try:
    import exists
except Exception, e:
    print "None on exists", sys.exc_info()[2].tb_next == None

try:
    import notexists
except Exception, e:
    print "None on notexists", sys.exc_info()[2].tb_next == None

>>> None on exists False
>>> None on notexists True
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top