我想导入一堆库并捕获异常。
如果我只有1个尝试catch块,我会得到1个异常(第一个)。是否存在迭代所有库的模式,并且每个缺少的lib都有一个单独的例外?
#!/usr/bin/env python
try: import sys
except: print sys.exc_info()
try: import numpy as np
except: print sys.exc_info()
try: import scipy as sp
except: print sys.exc_info()
try: import os as os
except: print sys.exc_info()
try: from operator import itemgetter
except: print sys.exc_info()
try: import socket
except: print sys.exc_info()
try: import logging
except: print sys.exc_info()
try: from time import gmtime, strftime
except: print sys.exc_info()
答案 0 :(得分:8)
您可以使用__import__
动态导入模块,允许您 - 除其他外 - 通过迭代列表及其名称来导入模块。
例如:
libnames = ['numpy', 'scipy', 'operator']
for libname in libnames:
try:
lib = __import__(libname)
except:
print sys.exc_info()
else:
globals()[libname] = lib
您可以将其扩展为处理import ... as ...
和from ... import ...
表单,或者稍后手动执行分配,即:
np = numpy
sp = scipy
itemgetter = operator.itemgetter
答案 1 :(得分:6)
虽然很常见,但不鼓励采用以下简易设计模式及其变体:
# BAD, hides circular import etc. nested errors
try:
import moolib
except ImportError:
raise ImportError("You must install moolib from http://moo.example.com in order to run this app")
而是使用Python包管理器来检查libray是否可用:
# GOOD
import pkg_resources
try:
pkg_resources.get_distribution('plone.dexterity')
except pkg_resources.DistributionNotFound:
HAS_DEXTERITY = False
else:
HAS_DEXTERITY = True
有关该主题的更多信息,请点击此处
正如上面的评论指出的那样,Python标准库模块(stdlib)始终可用,除非您在具有精简运行时的嵌入式环境中运行Python。
答案 2 :(得分:0)
您可以执行以下操作:
try:
import sys
import os.path
from logging import handlers
except ImportError as L_err:
print("ImportError: {0}".format(L_err))
raise L_err