在 Python 中,import does_not_exist
raisesImportError
和
import exists
exists.py
:
import does_not_exist
也会提高ImportError
。
我应该如何区分代码?
在 Python 中,import does_not_exist
raisesImportError
和
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 的 ImportError 的功能请求吗?有一个模块名称的变量肯定会很方便..
您可以使用回溯的 tb_next。如果异常发生在另一个模块上,它将与 None 不同
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