python 导入模块(使用程序导入模块,并简单对错误处理)

版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,加上原文链接即可~~ https://blog.csdn.net/hpulfc/article/details/83412234

在python 中如果需要导入一些模块,可以使用import xxx 或者使用from xx import xx 。只有这一种方式吗,当然不是,还有一种就是使用代码将一些模块导入。使用到的是 ` importlib ` 这个模块。

一般用法:

import importlib

importlib.import_module("module_name")

如果是要在某些项目中使用,可以参考下面的方式,其中包含了错误的一些处理。

# coding=utf8
from __future__ import print_function
__author__ = 'Administrator'

import six
import importlib

modules = [
    "module_test",
    "x"
]


def _py_err_msg(module):
    if six.PY2:
        err_msg = "No module named %s" % module.split(".")[-1]
    else:
        err_msg = "No module named '%s'" % module
    return err_msg


def _handle_error(errors, log_all=True):
    if not errors:
        return

    err_msg = "SKIP IMPORT MODULES {num_missing} "
    print(err_msg.format(num_missing=len(errors)))

    for _module, error in errors:
        err_str = str(error)
        if err_str != _py_err_msg(_module):
            print("From module %s ", _module)
            raise error
        if log_all:
            print("Did not import module: %s; Cause: %s" % (_module, err_str))


_errors = []
for _module in modules:
    try:
        importlib.import_module(_module)
    except ImportError as error:
        _errors.append((_module, error))
_handle_error(_errors)

# 测试这个导入模块,只需要把这个模块 导入 不会break 就表示 这个导入模块正常

可以简单运行一下这段代码:

结果类似下面:

猜你喜欢

转载自blog.csdn.net/hpulfc/article/details/83412234
今日推荐