def load_template(file, name=""): loader = TemplateLoader(name, file) spec = machinery.ModuleSpec(name, loader, origin=file) spec.has_location = True template = loader.create_module(spec) loader.exec_module(template) return template
def find_spec(self, fullname, path=None, target=None): """Return our spec it it's one of our packages or None.""" if self.find_module(fullname): return machinery.ModuleSpec(fullname, self, is_package='.' not in fullname) return None
def find_spec( self, fullname: str, *args, **kwargs, ) -> Optional[machinery.ModuleSpec]: if fullname.startswith(TOP_LEVEL_NAME): return machinery.ModuleSpec(name=fullname, loader=self, is_package=fullname == TOP_LEVEL_NAME) return None
def find_spec( self, fullname: str, path: tp.Optional[tp.Sequence[tp.Union[bytes, str]]] = None, target: tp.Optional[types.ModuleType] = None) \ -> tp.Optional[_ilm.ModuleSpec]: module_parts = fullname.split(".") if ".".join(module_parts[:2]) != ModelShim.SHIM_NAMESPACE: return None if fullname in sys.modules: return sys.modules[fullname].__spec__ ModelShim._log.info(f"Shim module load [{fullname}]") # Create namespace pkgs for trac.shim and trac.shim._x if len(module_parts) == 2 or len(module_parts) == 3: spec = _ilm.ModuleSpec(fullname, origin=None, is_package=True, loader=None) return spec shim_name = ".".join(module_parts[:3]) shim_path = pathlib.Path(self._shim_map[shim_name]) shim_module_path = shim_path.joinpath(module_parts[3] + ".py") if shim_module_path.exists() and shim_module_path.is_file(): shim_module = ".".join(module_parts[:4]) shim_module_loader = ModelShim.ModelSourceLoader( shim_module, str(shim_module_path)) spec = _ilm.ModuleSpec(shim_module, origin=str(shim_module_path), loader=shim_module_loader) return spec return None
def find_spec(self, mod_name, target=None): spec = None loader = self.find_module(mod_name) if loader: spec = util.spec_from_loader(mod_name, loader) else: dir_path = join(self.prefix, mod_name.rpartition(".")[2]) if self.isdir(dir_path): # Possible namespace package. spec = machinery.ModuleSpec(mod_name, None) spec.submodule_search_locations = [ join(self.extract_root, dir_path) ] return spec
def find_spec(self, fullname: str, path: str, target: Optional[str] = None) -> machinery.ModuleSpec: """ Locate the file in GCS. The "spec" should then be fullname = fullname path = location in GCS, should be hardwired in config """ if 'postprocessor' not in fullname: return None # we don't handle this this else: return machinery.ModuleSpec(fullname, PostProcessorLoader())
def find_spec(self, fullname: str, path, target) -> typing.Optional[machinery.ModuleSpec]: """Return module spec if asked for component module. Args: fullname: Module full name. path: module path (unused). target: module target (unused). Returns: Component module spec or nothing. """ if fullname == self._name: LOGGER.debug('Injecting component module loader') return machinery.ModuleSpec(fullname, self._loader) return None
def create_package(file, path, is_package=True, contents=()): class Reader(ResourceReader): def get_resource_reader(self, package): return self def open_resource(self, path): self._path = path if isinstance(file, Exception): raise file else: return file def resource_path(self, path_): self._path = path_ if isinstance(path, Exception): raise path else: return path def is_resource(self, path_): self._path = path_ if isinstance(path, Exception): raise path for entry in contents: parts = entry.split('/') if len(parts) == 1 and parts[0] == path_: return True return False def contents(self): if isinstance(path, Exception): raise path # There's no yield from in baseball, er, Python 2. for entry in contents: yield entry name = 'testingpackage' # Unforunately importlib.util.module_from_spec() was not introduced until # Python 3.5. module = types.ModuleType(name) loader = Reader() spec = machinery.ModuleSpec( name, loader, origin='does-not-exist', is_package=is_package) module.__spec__ = spec module.__loader__ = loader return module
def find_spec(self, full_module_name, search_path, target=None): _import_debug("Finding module spec for module_name: ", full_module_name) if search_path is None: _import_debug("Given searchpath is None, using sys.path") search_path = sys.path modulename = full_module_name.rsplit(".", 1)[-1] filename = modulename + ".aky" _import_debug("using search path: ", search_path) for path in search_path: if path == '': path = os.getcwd() filepath = os.path.join(path, filename) is_package = False if not os.path.isfile(filepath): filepath = os.path.join(path, modulename, "__init__.aky") is_package = True if os.path.isfile(filepath): _import_debug("Found .aky file: ", filepath) spec = imach.ModuleSpec( # name name=full_module_name, # loader loader=AnokyLoader(full_module_name, filepath), origin=filepath, is_package=is_package # __cached__=pycpath, # etc. ) if is_package: spec.submodule_search_locations = [ os.path.join(path, modulename) ] spec.has_location = True return spec _import_debug("Failed to find any .aky file!") return None
def find_spec(cls, fullname, path=None, target=None): if fullname == SUBMOD_NAME: spec = machinery.ModuleSpec(fullname, cls) return spec
def __init__(self, modname, connect_str, mapped_classes, modifiers, with_create=False, with_echo=False, drop_first=False, replace_module=False, **kwargs): if not replace_module: if modname in sys.modules: raise FlycastException( "There's already a module named {} so flycast can't create " "a new one with the same name unless you make the Casting " "with replace_module=True".format(modname)) self.session_factory = None self.modname = modname self.connect_str = connect_str self.mapped_classes = mapped_classes self.modifiers = modifiers self.with_build = with_create self.with_echo = with_echo self.with_delete = drop_first self.engine = create_engine(connect_str, echo=with_echo, **kwargs) # dynamically create a module spec = machinery.ModuleSpec(modname, None) self.module = util.module_from_spec(spec) sys.modules[self.modname] = self.module # set up the declarative base class self.module.declarative_base = declarative_base self.module.Base = self.module.declarative_base() # load the mapped classes into the module for mapped_class_name, class_cols in mapped_classes.items(): if "__tablename__" not in class_cols: raise FlycastException( "Mapped class dict {} does not have a " "__tablename__ key".format(mapped_class_name)) setattr(self.module, mapped_class_name, type(mapped_class_name, (self.module.Base, ), class_cols)) # TODO: put the modifiers in the module here if with_create: if drop_first: try: self.module.Base.metadata.drop_all(self.engine) except: pass self.module.Base.metadata.create_all(self.engine) # now activate the model self.session_factory = scoped_session(sessionmaker(bind=self.engine)) self.session_factory.configure(bind=self.engine) if self.module.Base.metadata.bind != self.engine: self.module.Base.metadata.bind = self.engine if with_echo: self.module.Base.metadata.bind.echo = True
def find_spec(self, fullname, path=None, target=None): return machinery.ModuleSpec(fullname, self)
def find_spec(self, fullname, path, target=None): modname = fullname.split(".")[-1] if self.base_name in modname: prefix, suffix = modname.split(self.base_name, 1) return imach.ModuleSpec(name=fullname, loader=_DynamicLambLoader(prefix, suffix))
# -*- coding: utf-8 -*- """ Created on Mon Jan 14 16:35:37 2019 @author: cagurl01 """ import importlib.machinery as impmach from importlib.util import module_from_spec loader = impmach.SourceFileLoader('csvdata', '../csvdata/csvdata.py') spec = impmach.ModuleSpec('csvdata', loader) csvdata = module_from_spec(spec) loader.exec_module(csvdata) import openpyxl as opx import os from copy import copy from configparser import ConfigParser # NOTE: May need to include openpyxl module import above # Cell merge patch start from openpyxl.worksheet import Worksheet from openpyxl.reader.worksheet import WorkSheetParser from openpyxl.worksheet.merge import MergeCells from openpyxl.worksheet.cell_range import CellRange # from openpyxl.utils import range_boundaries ### Included in monkey patch but unused class AccessError(Exception): def __init__(self, message): super().__init__(message)
import importlib from importlib import (machinery, util) import os import sys APP_NAMESPACE = '__app__' FLASK_PROJECT_PATH = os.fspath(os.path.join(os.path.dirname(__file__))) if __name__ == '__main__': ns_spec = machinery.ModuleSpec(APP_NAMESPACE, None) ns_spec.submodule_search_locations = [FLASK_PROJECT_PATH] ns_pkg = util.module_from_spec(ns_spec) sys.modules[APP_NAMESPACE] = ns_pkg from __app__.project import app app.run(host='0.0.0.0', port=9527, debug=True)