##################### ### classloader.py ### ####################
import sys, types
def _get_mod(modulePath):try:aMod = sys.modules[modulePath]if not isinstance(aMod, types.ModuleType):raise KeyErrorexcept KeyError:# The last [''] is very important!aMod = __import__(modulePath, globals(), locals(), [''])sys.modules[modulePath] = aModreturn aMod
def _get_func(fullFuncName):"""Retrieve a function object from a full dotted-package name."""
# Parse out the path, module, and functionlastDot = fullFuncName.rfind(u".")funcName = fullFuncName[lastDot + 1:]modPath = fullFuncName[:lastDot]
aMod = _get_mod(modPath)aFunc = getattr(aMod, funcName)
# Assert that the function is a *callable* attribute.assert callable(aFunc), u"%s is not callable." % fullFuncName
# Return a reference to the function itself,# not the results of the function.return aFunc
def _get_class(fullClassName, parentClass=None):"""Load a module and retrieve a class (NOT an instance).
If the parentClass is supplied, className must be of parentClassor a subclass of parentClass (or None is returned)."""aClass = _get_func(fullClassName)
# Assert that the class is a subclass of parentClass.if parentClass is not None:if not issubclass(aClass, parentClass):raise TypeError(u"%s is not a subclass of %s" %(fullClassName, parentClass))
# Return a reference to the class itself, not an instantiated object.return aClass
######################## Usage ########################
class StorageManager: passclass StorageManagerMySQL(StorageManager): pass
def storage_object(aFullClassName, allOptions={}):aStoreClass = _get_class(aFullClassName, StorageManager)return aStoreClass(allOptions)
import pkgutilimport importlib
packages = pkgutil.walk_packages(path='.')for importer, name, is_package in packages:mod = importlib.import_module(name)# do whatever you want with module now, it's been imported!
import impimport sys
def __import__(name, globals=None, locals=None, fromlist=None):# Fast path: see if the module has already been imported.try:return sys.modules[name]except KeyError:pass
# If any of the following calls raises an exception,# there's a problem we can't handle -- let the caller handle it.
fp, pathname, description = imp.find_module(name)
try:return imp.load_module(name, fp, pathname, description)finally:# Since we may exit via an exception, close fp explicitly.if fp:fp.close()
def import_module_from_file(full_path_to_module):"""Import a module given the full path/filename of the .py file
Python 3.4
"""
module = None
try:
# Get module name and path from full pathmodule_dir, module_file = os.path.split(full_path_to_module)module_name, module_ext = os.path.splitext(module_file)
# Get module "spec" from filenamespec = importlib.util.spec_from_file_location(module_name,full_path_to_module)
module = spec.loader.load_module()
except Exception as ec:# Simple error printing# Insert "sophisticated" stuff hereprint(ec)
finally:return module
import sysimport importlib.machinery
def load_module(name, filename):# If the Loader finds the module name in this list it will use# module_name.__file__ instead so we need to delete it hereif name in sys.modules:del sys.modules[name]loader = importlib.machinery.ExtensionFileLoader(name, filename)module = loader.load_module()locals()[name] = moduleglobals()[name] = module
load_module('something', r'C:\Path\To\something.pyd')something.do_something()
import importlib
dirname, basename = os.path.split(pyfilepath) # pyfilepath: '/my/path/mymodule.py'sys.path.append(dirname) # only directories should be added to PYTHONPATHmodule_name = os.path.splitext(basename)[0] # '/my/path/mymodule.py' --> 'mymodule'module = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for "module_name")
import pathlib
def likely_python_module(filename):'''Given a filename or Path, return the "likely" python module name. That is, iteratethe parent directories until it doesn't contain an __init__.py file.
:rtype: str'''p = pathlib.Path(filename).resolve()paths = []if p.name != '__init__.py':paths.append(p.stem)while True:p = p.parentif not p:breakif not p.is_dir():break
inits = [f for f in p.iterdir() if f.name == '__init__.py']if not inits:break
paths.append(p.stem)
return '.'.join(reversed(paths))
import os, sys, inspect, copy
SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')SOURCE_DIR = os.path.dirname(SOURCE_FILE)
print("test::SOURCE_FILE: ", SOURCE_FILE)
# portable import to the global spacesys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directoryimport tacklelib as tkl
tkl.tkl_init(tkl)
# cleanupdel tkl # must be instead of `tkl = None`, otherwise the variable would be still persistsys.path.pop()
tkl_import_module(SOURCE_DIR, 'testlib.py')
print(globals().keys())
testlib.base_test()testlib.testlib_std1.std1_test()testlib.testlib_std1.testlib_std2.std2_test()#testlib.testlib.std3.std3_test() # does not reachable directly ...getattr(globals()['testlib'], 'testlib.std3').std3_test() # ... but reachable through the `globals` + `getattr`
tkl_import_module(SOURCE_DIR, 'testlib.py', '.')
print(globals().keys())
base_test()testlib_std1.std1_test()testlib_std1.testlib_std2.std2_test()#testlib.std3.std3_test() # does not reachable directly ...globals()['testlib.std3'].std3_test() # ... but reachable through the `globals` + `getattr`
from thesmuggler import smuggle
# À la `import weapons`weapons = smuggle('weapons.py')
# À la `from contraband import drugs, alcohol`drugs, alcohol = smuggle('drugs', 'alcohol', source='contraband.py')
# À la `from contraband import drugs as dope, alcohol as booze`dope, booze = smuggle('drugs', 'alcohol', source='contraband.py')