Importing Python libraries and gracefully handling if they are not availalble

时光毁灭记忆、已成空白 提交于 2019-11-30 14:28:46

You can use __import__ to dynamically import modules, allowing you to - among other things - import modules by iterating a list with their names.

For example:

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

You can either extend that to handle the import ... as ... and from ... import ... forms or just do the assignments later manually, ie.:

np = numpy
sp = scipy
itemgetter = operator.itemgetter

Though common, the following easy design pattern and its variations are discouraged:

  # 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")

Instead use the Python package manager to check if a libray is available:

# GOOD
import pkg_resources

try:
    pkg_resources.get_distribution('plone.dexterity')
except pkg_resources.DistributionNotFound:
    HAS_DEXTERITY = False
else:
    HAS_DEXTERITY = True

More about the topic can be found here

As the comments above point out, Python standard library modules (stdlib) are always available UNLESS you run Python in an embedded environment with stripped down run-time.

Pipo

You can doing as the following:

try:
    import sys 
    import os.path
    from logging import handlers
except ImportError as L_err:
    print("ImportError: {0}".format(L_err))
    raise L_err
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!