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

在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 就表示 这个导入模块正常

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

结果类似下面:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值