且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

由于在python中找不到模块或模块本身的错误导入而区分ImportError?

更新时间:2023-08-21 23:09:10

您知道如果模块不存在,导入错误消息会是什么样的,所以只需检查一下:

You know what the import error message will look like if the module doesn't exist so just check for that:

try:
    module = module_name + '.tests'
    __import__(module)
except ImportError, e:
    if e.args and e.args[0] == 'No module named ' + module:
        print(module, 'does not exist')
    else:
        print(module, 'failed to import')