¿Cómo distingo “módulo no encontrado” de “módulo lanzó una excepción” en la ImportError?

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

  •  13-09-2019
  •  | 
  •  

Pregunta

En Python, import does_not_exist plantea ImportError, y

import exists

exists.py:

import does_not_exist

también elevará ImportError.

¿Cómo debo decir la diferencia en el código?

¿Fue útil?

Solución

El único método que conozco es comprobar si el modulename nivel superior "existe" en el mensaje de la excepción o no:

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

Podría ser esta una de estas solicitudes para ImportError de Python? Tener una variable para el nombre del módulo sin duda sería conveniente ..

Otros consejos

Puede utilizar el tb_next del rastreo. Será diferente de None si la excepción se produjo en otro módulo

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top