我有一个可选择存在模块的情况。如果它不存在,那就没问题。
我写了这个:
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
然后我意识到这没有实现我想要的,因为它掩盖了文件存在但它包含错误的情况下的错误。
如何安全导入模块(如果存在)...但如果包含模块则报告错误?
答案 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