Source From Here
Question
I need to know if a python module exists, without importing it.
How-To
Python2
To check if import can find something in python2, using imp:
To find dotted imports, you need to do more:
You can also use
pkgutil.find_loader (more or less the same as the python3 part):
Python3 <= 3.3
You should use importlib, How I went about doing this was:
My expectation being, if you can find a loader for it, then it exists. You can also be a bit more smart about it, like filtering out what loaders you will accept. For example:
Python3 >= 3.4
In Python3.4 importlib.find_loader python docs was deprecated in favour of importlib.util.find_spec. Really, you need to choose any concrete implementation, recomended is the importlib.util.find_spec one. There are others like importlib.machinery.FileFinder, which is useful if you're after a specific file to load. Figuring out how to use them is beyond the scope of this.
This also works with relative imports but you must supply the starting package, so you could also do:
WARNING
When trying to find a submodule, it will import the parent module (for all of the above methods)!
Question
I need to know if a python module exists, without importing it.
How-To
Python2
To check if import can find something in python2, using imp:
- import imp
- try:
- imp.find_module('eggs')
- found = True
- except ImportError:
- found = False
- import imp
- try:
- 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 = True
- except ImportError:
- found = False
- import pkgutil
- eggs_loader = pkgutil.find_loader('eggs')
- found = eggs_loader is not None
You should use importlib, How I went about doing this was:
- 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)
In Python3.4 importlib.find_loader python docs was deprecated in favour of importlib.util.find_spec. Really, you need to choose any concrete implementation, recomended is the importlib.util.find_spec one. There are others like importlib.machinery.FileFinder, which is useful if you're after a specific file to load. Figuring out how to use them is beyond the scope of this.
- 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 None
- spam_spec.name == "eggs.spam"
When trying to find a submodule, it will import the parent module (for all of the above methods)!
沒有留言:
張貼留言