拉莫斯之舞
Python2要检查导入是否可以在python2中找到某些内容,请使用 impimport imptry:
imp.find_module('eggs')
found = Trueexcept ImportError:
found = False要查找虚线导入,您需要执行更多操作:import imptry:
spam_info = imp.find_module('spam')
spam = imp.load_module('spam', *spam_info)
imp.find_module('eggs', spam.__path__) # __path__ is already a list
found = Trueexcept ImportError:
found = False你也可以使用pkgutil.find_loader(或多或少与python3部分相同import pkgutil
eggs_loader = pkgutil.find_loader('eggs')found = eggs_loader is not NonePython3Python3≤3.3您应该使用importlib,我是如何做到这一点的:import importlib
spam_loader = importlib.find_loader('spam')found = spam_loader is not None我的期望是,如果你能为它找到装载机,那么它就存在了。你也可以更聪明一点,比如过滤掉你会接受的装载机。例如:import importlib
spam_loader = importlib.find_loader('spam')# only accept it as valid if there is a source file for the module - no bytecode only.found = issubclass(type(spam_loader), importlib.machinery.SourceFileLoader)Python3≥3.4在Python3.4中,importlib.find_loader python docs被弃用了importlib.util.find_spec。推荐的方法是importlib.util.find_spec。还有其他类似的importlib.machinery.FileFinder,如果您要加载特定文件,这将非常有用。弄清楚如何使用它们超出了这个范围。import importlib
spam_spec = importlib.util.find_spec("spam")found = spam_spec is not None这也适用于相对导入但你必须提供起始包,所以你也可以这样做:import importlib
spam_spec = importlib.util.find_spec("..spam", package="eggs.bar")found = spam_spec is not Nonespam_spec.name == "eggs.spam"虽然我确信这样做有理由 - 我不确定它会是什么。警告在尝试查找子模块时,它将导入父模块(对于所有上述方法)!food/
|- __init__.py |- eggs.py## __init__.pyprint("module food loaded")## eggs.pyprint("module eggs")were you then to run>>> import importlib>>> spam_spec = importlib.find_spec("food.eggs")module food loadedModuleSpec(name='food.eggs', loader=<_frozen_importlib.SourceFileLoader object at 0x10221df28>, origin='/home/user/food/eggs.py')欢迎回答这个问题致谢@rvighne for importlib@ lucas-guido for python3.3 + depricating find_loader@enpenax用于python2.7中的pkgutils.find_loader行为