Error handling when importing modules

后端 未结 3 1772
一个人的身影
一个人的身影 2020-12-09 14:37

This probably has an obvious answer, but I\'m a beginner. I\'ve got a \"module\" (really just a file with a bunch of functions I often use) at the beginning of which I impo

3条回答
  •  情话喂你
    2020-12-09 15:26

    As advocated by https://stackoverflow.com/a/20228312/1587329 [modified, with an edit from @Ian]

    from importlib import import_module
    
    named_libs = [('numpy', 'np'), ('matplotlib', 'mp')] # (library_name, shorthand)
    for (name, short) in named_libs:
        try:
            lib = import_module(name)
        except:
            print sys.exc_info()
        else:
            globals()[short] = lib
    

    imports all libraries in named_libs. The first string is the library name, the second the shorthand. For unnamed libraries, you can use the original:

    from importlib import import_module     
    
    libnames = ['numpy', 'scipy', 'operator']
    for libname in libnames:
        try:
            lib = import_module(libname)
        except:
            print sys.exc_info()
        else:
            globals()[libname] = lib
    

提交回复
热议问题