如何区分导入错误,因为该文件不存在,与它不解析

时间:2016-01-08 10:27:12

标签: python import exception-handling

我有一个可选择存在模块的情况。如果它不存在,那就没问题。

我写了这个:

try:
    import debug_trace
    print "[FEATURE_TEST] ... loaded custom debug traces, from %s" % debug_trace.__file__
except ImportError:
    # The file "debug_trace.py" probably doesn't exist
    pass

然后我意识到这没有实现我想要的,因为它掩盖了文件存在但它包含错误的情况下的错误。

如何安全导入模块(如果存在)...但如果包含模块则报告错误?

1 个答案:

答案 0 :(得分:1)

看看这个

[How to check if a python module exists without importing it

因此,在您的特定情况下,我会将Thomas的答案和您的代码结合起来

import imp
try:
    imp.find_module('debug_trace')
    found = True
except ImportError:
    print "Module debug_trace not found"
    found = False
    pass

if found:
    try:
        import debug_trace
        print "[FEATURE_TEST] ... loaded custom debug traces, from %s" % debug_trace.__file__
    except ImportError:
        # The file "debug_trace.py" exists but importation fails
        pass