Source From Here
Question
I need to know if a python module exists, without importing it. Importing something that might not exist (not what I want):
How-To
To check if import can find something in python2, using imp:
To find dotted imports, you need to do more:
For a full path module (
including dot), below is an example for reference:
Here "demo.faq.CheckModules" is a local module for testing. A execution sample output will be:
Python3 wants you to 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
Question
I need to know if a python module exists, without importing it. Importing something that might not exist (not what I want):
- try:
- import eggs
- except ImportError:
- pass
To check if import can find something in python2, using imp:
- # -*- coding: utf-8 -*-
- import imp
- def chkModExist(mn):
- try:
- imp.find_module(mn)
- return True
- except ImportError:
- return False
- for mn in ['egg', 'selenium', 'os']:
- print "Module '{0}' exist? {1}".format(mn, chkModExist(mn))
- 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
- # -*- coding: utf-8 -*-
- import imp
- import os.path
- def chkModExist(mn, path=None):
- try:
- #print "Search moudle='{0}' from '{1}'...".format(mn, path)
- if path is None:
- m_info=imp.find_module(mn)
- else:
- m_info=imp.find_module(mn, [path])
- return (True, m_info)
- except ImportError:
- return False
- md = {}
- print "\t[Info] Loading desired modules..."
- for mn in ['egg', 'selenium', 'os', 'demo.faq.CheckModules']:
- mn_dot = mn.split(".")
- lm=None
- for sm in mn_dot:
- if lm:
- if "__init__.py" in lm.__file__:
- rt=chkModExist(sm, os.path.dirname(lm.__file__))
- else:
- rt=chkModExist(sm)
- if rt:
- m_info = rt[1]
- m=imp.load_module(sm, *m_info)
- print "\t\tLoading module...{0}/{1}".format(m, m.__file__)
- lm=m
- else:
- print "\t\tModule '{0}' doesn't exist ({1})".format(mn, sm)
- lm=None
- break
- if lm:
- md[mn]=lm
- print "\t[Info] Leverage loaded module 'os' to show env:\n%s" % md['os'].environ
Python3 wants you to 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)
沒有留言:
張貼留言