1

在 Python 中,import does_not_existraisesImportError

import exists

exists.py

import does_not_exist

也会提高ImportError

我应该如何区分代码?

4

2 回答 2

3

我知道的唯一方法是检查顶级模块名“存在”是否在异常消息中:

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

这可能是 Python 的 ImportError 的功能请求吗?有一个模块名称的变量肯定会很方便..

于 2009-12-07T14:43:14.213 回答
2

您可以使用回溯的 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
于 2009-12-07T15:07:24.907 回答