当前位置: 首页>>代码示例>>Python>>正文


Python SourceFileLoader.load_module方法代码示例

本文整理汇总了Python中importlib.machinery.SourceFileLoader.load_module方法的典型用法代码示例。如果您正苦于以下问题:Python SourceFileLoader.load_module方法的具体用法?Python SourceFileLoader.load_module怎么用?Python SourceFileLoader.load_module使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在importlib.machinery.SourceFileLoader的用法示例。


在下文中一共展示了SourceFileLoader.load_module方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_race

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def load_race(name):
    ensure_directories()
    base_name = name.lower()
    file_name = base_name.replace('-', '_') + ".py"
    class_name = ''.join(part.capitalize() for part in base_name.split('-'))

    try:
        # from this library
        Race = getattr(__import__("dndraces"), class_name)
    except AttributeError:
        # Don't make __pycache__ file in the races directories
        sys.dont_write_bytecode = True
        try:
            # from $HOME
            loader = SourceFileLoader(class_name,
                                      os.path.join(HOME_RACES, file_name))
            races = loader.load_module()
            Race = getattr(races, class_name)
        except FileNotFoundError:
            try:
                # from /etc
                loader = SourceFileLoader(class_name,
                                          os.path.join(ETC_RACES, file_name))
                races = loader.load_module()
                Race = getattr(races, class_name)
            except FileNotFoundError:
                msg = "Can not find class for " + name + "\n"
                msg += 'Looking for class "' + class_name + '" in ' + file_name
                raise FileNotFoundError()

    return Race
开发者ID:chielk,项目名称:dndmake,代码行数:33,代码来源:load.py

示例2: test_all_imports_py

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def test_all_imports_py():
   """ Tests: test_all_imports_py: for syntax correctness and internal imports
   """
   print('::: TEST: test_all_imports_py()')
   all_modules_path = []
   for root, dirnames, filenames in os_walk(ROOT_PACKAGE_PATH):
      all_modules_path.extend(glob(root + '/*.py'))
   for py_module_file_path in all_modules_path:
      module_filename = path_basename(py_module_file_path)
      module_filename_no_ext = path_splitext(module_filename)[0]

      py_loader = SourceFileLoader(module_filename_no_ext, py_module_file_path)
      py_loader.load_module(module_filename_no_ext)
开发者ID:peter1000,项目名称:JqPyCharts,代码行数:15,代码来源:test_imports.py

示例3: _import_plugin_from_path

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
 def _import_plugin_from_path(self, name, path):
     try:
         mname = "hyperspyui.plugins." + name
         if sys.version_info >= (3, 5):
             import importlib.util
             spec = importlib.util.spec_from_file_location(mname, path)
             module = importlib.util.module_from_spec(spec)
             spec.loader.exec_module(module)
         else:
             from importlib.machinery import SourceFileLoader
             loader = SourceFileLoader(mname, path)
             loader.load_module()
     except Exception:
         self.warn("import", path)
开发者ID:vidartf,项目名称:hyperspyUI,代码行数:16,代码来源:pluginmanager.py

示例4: get_config

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def get_config(name, abspath):
    config = None
    files = os.listdir(abspath)
    if (name + '.yml') in files or (name + '.yaml') in files:
        cfile = name + '.yml'
        cfile = cfile if cfile in files else name + '.yaml'
        with open(os.path.join(abspath, cfile)) as f:
            config = yaml.load(f)
        logger.debug('used yaml')
    else:
        pyloader = SourceFileLoader(name, os.path.join(abspath, name + '.py'))
        pyloader.load_module()
        mod = sys.modules[name]
        config = getattr(mod, name)
        logger.debug('used dict')
    return config
开发者ID:risuoku,项目名称:suspend,代码行数:18,代码来源:__init__.py

示例5: load_settings

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def load_settings(cfg_path=None):
    """todo: Docstring for load_settings

    :param cfg_path: arg description
    :type cfg_path: type description
    :return:
    :rtype:
    """

    global settings

    cfg_path = cfg_path or _config['cfg_path']

    cfg_d = _config.copy()

    if os.path.exists(cfg_path):
        sfl = SourceFileLoader('upkg_cfg', cfg_path)
        cfg_mod = sfl.load_module()

        for m in inspect.getmembers(cfg_mod):
            if m[0][0] != '_':
                cfg_d[m[0]] = m[1]
        # end for m in inspect.getme

    # Make the paths absolute.
    cfg_d["cfg_path"] = _clean_path(cfg_d["cfg_path"])
    cfg_d["upkg_destdir"] = _clean_path(cfg_d["upkg_destdir"])

    settings = Namespace(**cfg_d)
开发者ID:jeffbuttars,项目名称:upkg,代码行数:31,代码来源:conf.py

示例6: get_info_from_module

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def get_info_from_module(target):
    """Load the module/package, get its docstring and __version__
    """
    log.debug("Loading module %s", target.file)
    sl = SourceFileLoader(target.name, str(target.file))
    with _module_load_ctx():
        m = sl.load_module()
    docstring = m.__dict__.get('__doc__', None)
    if not docstring: 
        raise NoDocstringError('Cannot package module without docstring. '
                                'Please add a docstring to your module.')
    module_version = m.__dict__.get('__version__', None)
    if not module_version: 
        raise NoVersionError('Cannot package module without a version string. '
                             'Please define a `__version__="x.y.z"` in your module.')
    if not isinstance(module_version, str):
        raise InvalidVersion('__version__ must be a string, not {}.'
                                .format(type(module_version)))
    if not module_version[0].isdigit():
        raise InvalidVersion('__version__ must start with a number. It is {!r}.'
                                .format(module_version))

    docstring_lines = docstring.lstrip().splitlines()
    return {'summary': docstring_lines[0],
            'version': m.__version__}
开发者ID:aragilar,项目名称:flit,代码行数:27,代码来源:common.py

示例7: loadPlugins

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def loadPlugins():
	modules = getPythonScriptModules()
	print("Found python modules to scan for relink lookup %s" % len(modules))
	# print("Modules:")
	# modules.sort()
	# for module in modules:
	# 	print('	', module)
	ret = {}

	for fPath, modName in modules:
		# print("Loading", fPath, modName)
		try:
			loader = SourceFileLoader(modName, fPath)
			mod = loader.load_module()
			plugClasses = findPluginClass(mod, 'Scrape')
			for key, pClass in plugClasses:
				if key in ret:
					raise ValueError("Two plugins providing an interface with the same name? Name: '%s'" % key)
				ret[key] = pClass
		except AttributeError:
			print("Attribute error!", modName)
			traceback.print_exc()
			pass
		except ImportError:
			print("Import error!", modName)
			traceback.print_exc()
			pass
	return ret
开发者ID:GJdan,项目名称:MangaCMS,代码行数:30,代码来源:RelinkLookup.py

示例8: load_module_from_file

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
 def load_module_from_file(name, path):
     try:
         loaded = SourceFileLoader(name, path)
         if isinstance(loaded, types.ModuleType):
             return loaded, None
         return loaded.load_module(), None
     except Exception as error:
         return None, error
开发者ID:Peoplecantfly,项目名称:netdata,代码行数:10,代码来源:loaders.py

示例9: load_provider

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
 def load_provider(self, manage_py):
     from plainbox import provider_manager
     from providerbackend import fake_provider_manager
     provider_manager.setup = fake_provider_manager.setup
     loader = SourceFileLoader('manage', manage_py)
     loader.load_module()
     if len(fake_provider_manager.all_setup_kwargs) == 0:
         raise ValueError("provider not defined")
     kwargs = fake_provider_manager.all_setup_kwargs.pop()
     location = os.path.dirname(os.path.abspath(manage_py))
     definition = Provider1Definition()
     definition.location = location
     definition.name = kwargs.get('name', None)
     definition.version = kwargs.get('version', None)
     definition.description = kwargs.get('description', None)
     definition.gettext_domain = kwargs.get('gettext_domain', Unset)
     return Provider1.from_definition(definition, secure=False)
开发者ID:zyga,项目名称:plainboxproviders,代码行数:19,代码来源:models.py

示例10: return_module

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
    def return_module(self, name='test'):
        file_name = path.join(self.out_dir.name, name + '.py')

        sys_path.append(self.out_dir.name)
        loader = SourceFileLoader(self._testMethodName, file_name)
        module = loader.load_module(self._testMethodName)
        sys_path.remove(self.out_dir.name)

        return module
开发者ID:Pr0Ger,项目名称:protobuf3,代码行数:11,代码来源:test_compiler.py

示例11: load_module_by_path

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
def load_module_by_path(fpath, module_name=None):
    if module_name is None:
        module_name = str(uuid())
    fpath = os.path.realpath(fpath)
    if os.path.isdir(fpath):
        fpath = os.path.join(fpath, '__init__.py')
    loader = SourceFileLoader(module_name, fpath)
    m = loader.load_module()
    return m
开发者ID:raffber,项目名称:wasp,代码行数:11,代码来源:util.py

示例12: load_doc_manager

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
        def load_doc_manager(path):
            name, _ = os.path.splitext(os.path.basename(path))
            try:
                from importlib.machinery import SourceFileLoader

                loader = SourceFileLoader(name, path)
                module = loader.load_module(name)
            except ImportError:
                module = imp.load_source(name, path)
            return module
开发者ID:rohitkn,项目名称:mongo-connector,代码行数:12,代码来源:connector.py

示例13: list_filaments

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
 def list_filaments(cls):
     filaments = {}
     for filament in os.listdir(FILAMENTS_DIR):
         path = os.path.join(FILAMENTS_DIR, filament)
         if path.endswith('.py'):
             name = os.path.basename(filament)[:-3]
             loader = SourceFileLoader(name, path)
             film = loader.load_module()
             filaments[name] = inspect.getdoc(film)
     return filaments
开发者ID:max3raza,项目名称:fibratus,代码行数:12,代码来源:filament.py

示例14: __init__

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
 def __init__(self, module_path, module_name):
     tyk.log( "Loading module: '{0}'".format(module_name), "info")
     self.module_path = module_path
     self.handlers = {}
     try:
         source = SourceFileLoader(module_name, self.module_path)
         self.module = source.load_module()
         self.register_handlers()
     except:
         tyk.log_error( "Middleware initialization error:" )
开发者ID:keyeMyria,项目名称:tyk,代码行数:12,代码来源:middleware.py

示例15: test_02

# 需要导入模块: from importlib.machinery import SourceFileLoader [as 别名]
# 或者: from importlib.machinery.SourceFileLoader import load_module [as 别名]
    def test_02(self):
        """
        Test Case 02:
        Try importing the magrathea script (Python>=3.4)

        Test is passed if a RuntimeError exception is raised.
        """
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'magrathea.py'))
        with self.assertRaises(RuntimeError):
            loader = SourceFileLoader('magrathea', path)
            __ = loader.load_module()
开发者ID:RootForum,项目名称:magrathea,代码行数:13,代码来源:test_magrathea.py


注:本文中的importlib.machinery.SourceFileLoader.load_module方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。