我如何区分上导入错误“模块抛出异常”,“模块找不到”?
-
13-09-2019 - |
题
在Python中,import does_not_exist
引发ImportError
,和
import exists
exists.py
:
import does_not_exist
也将提高ImportError
。
我应该如何告诉代码区别?
解决方案
我知道的唯一方法是,以检查是否顶层模块名“存在”是异常的消息或不:
try:
import exists
except ImportError as exc:
if "exists" in str(exc):
pass
else:
raise
这会是对Python的导入错误功能请求?具有用于模块名称的变量当然将是方便..
其他提示
可以使用traceback的tb_next。这将是从没有不同,如果异常另一模块上发生
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
不隶属于 StackOverflow