本文整理汇总了Python中importlib.machinery方法的典型用法代码示例。如果您正苦于以下问题:Python importlib.machinery方法的具体用法?Python importlib.machinery怎么用?Python importlib.machinery使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类importlib
的用法示例。
在下文中一共展示了importlib.machinery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _add_module_finder
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def _add_module_finder(self) -> None:
"""Add a custom finder to support Nest module import syntax.
"""
module_manager = self
class NamespaceLoader(importlib.abc.Loader):
def create_module(self, spec):
_, namespace = spec.name.split('.')
module = ModuleType(spec.name)
module_manager._update_namespaces()
meta = module_manager.namespaces.get(namespace)
module.__path__ = [meta['module_path']] if meta else []
return module
def exec_module(self, module):
pass
class NestModuleFinder(importlib.abc.MetaPathFinder):
def __init__(self):
super(NestModuleFinder, self).__init__()
self.reserved_namespaces = [
v[:-3] for v in os.listdir(os.path.dirname(os.path.realpath(__file__))) if v.endswith('.py')]
def find_spec(self, fullname, path, target=None):
if fullname.startswith('nest.'):
name = fullname.split('.')
if len(name) == 2:
if not name[1] in self.reserved_namespaces:
return importlib.machinery.ModuleSpec(fullname, NamespaceLoader())
sys.meta_path.insert(0, NestModuleFinder())
示例2: load_package
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def load_package(name, path):
"""**DEPRECATED**"""
if os.path.isdir(path):
extensions = (machinery.SOURCE_SUFFIXES[:] +
machinery.BYTECODE_SUFFIXES[:])
for extension in extensions:
path = os.path.join(path, '__init__'+extension)
if os.path.exists(path):
break
else:
raise ValueError('{!r} is not a package'.format(path))
spec = util.spec_from_file_location(name, path,
submodule_search_locations=[])
if name in sys.modules:
return _exec(spec, sys.modules[name])
else:
return _load(spec)
示例3: import_module_by_path
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def import_module_by_path(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
import imp
return imp.load_source(name, path)
elif sys.version_info[:2] <= (3, 4):
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, path).load_module()
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# ===================================================================
# --- others
# ===================================================================
示例4: load_package
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def load_package(name, path):
"""**DEPRECATED**"""
if os.path.isdir(path):
extensions = (machinery.SOURCE_SUFFIXES[:] +
machinery.BYTECODE_SUFFIXES[:])
for extension in extensions:
init_path = os.path.join(path, '__init__' + extension)
if os.path.exists(init_path):
path = init_path
break
else:
raise ValueError('{!r} is not a package'.format(path))
spec = util.spec_from_file_location(name, path,
submodule_search_locations=[])
if name in sys.modules:
return _exec(spec, sys.modules[name])
else:
return _load(spec)
示例5: getsourcefile
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
if any(filename.endswith(s) for s in all_bytecode_suffixes):
filename = (os.path.splitext(filename)[0] +
importlib.machinery.SOURCE_SUFFIXES[0])
elif any(filename.endswith(s) for s in
importlib.machinery.EXTENSION_SUFFIXES):
return None
if os.path.exists(filename):
return filename
# only return a non-existent filename if the module has a PEP 302 loader
if getattr(getmodule(object, filename), '__loader__', None) is not None:
return filename
# or it is in the linecache
if filename in linecache.cache:
return filename
示例6: isPackageDirectory
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def isPackageDirectory(dirname):
"""
Is the directory at path 'dirname' a Python package directory?
Returns the name of the __init__ file (it may have a weird extension)
if dirname is a package directory. Otherwise, returns False
"""
def _getSuffixes():
if _PY3:
import importlib
return importlib.machinery.all_suffixes()
else:
import imp
return list(zip(*imp.get_suffixes()))[0]
for ext in _getSuffixes():
initFile = '__init__' + ext
if os.path.exists(os.path.join(dirname, initFile)):
return initFile
return False
示例7: loadFile
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def loadFile(self, fileName, recurse=False):
"""
Load a file, and then the tests in that file.
@param fileName: The file name to load.
@param recurse: A boolean. If True, inspect modules within packages
within the given package (and so on), otherwise, only inspect
modules in the package itself.
"""
from importlib.machinery import SourceFileLoader
name = reflect.filenameToModuleName(fileName)
try:
module = SourceFileLoader(name, fileName).load_module()
return self.loadAnything(module, recurse=recurse)
except OSError:
raise ValueError("{} is not a Python file.".format(fileName))
示例8: _importlib_import_modpath
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def _importlib_import_modpath(modpath): # nocover
"""
Alternative to import_module_from_path using importlib mechainsms
"""
dpath, rel_modpath = split_modpath(modpath)
modname = modpath_to_modname(modpath)
if six.PY2: # nocover
import imp
module = imp.load_source(modname, modpath)
elif sys.version_info[0:2] <= (3, 4): # nocover
if sys.version_info[0:2] <= (3, 2):
raise AssertionError('3.0 to 3.2 is not supported')
from importlib.machinery import SourceFileLoader
module = SourceFileLoader(modname, modpath).load_module()
else:
import importlib.util
spec = importlib.util.spec_from_file_location(modname, modpath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
示例9: test_issue8202
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def test_issue8202(self):
# Make sure package __init__ modules see "-m" in sys.argv0 while
# searching for the module to execute
with temp_dir() as script_dir:
with support.change_cwd(path=script_dir):
pkg_dir = os.path.join(script_dir, 'test_pkg')
make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
script_name = _make_test_script(pkg_dir, 'script')
rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
if verbose > 1:
print(repr(out))
expected = "init_argv0==%r" % '-m'
self.assertIn(expected.encode('utf-8'), out)
self._check_output(script_name, rc, out,
script_name, script_name, '', 'test_pkg',
importlib.machinery.SourceFileLoader)
示例10: find_spec
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def find_spec(self, name, path=None, target=None):
if self._writing_pyc:
return None
state = self.config._assertstate
if self._early_rewrite_bailout(name, state):
return None
state.trace("find_module called for: %s" % name)
spec = self._find_spec(name, path)
if (
# the import machinery could not find a file to import
spec is None
# this is a namespace package (without `__init__.py`)
# there's nothing to rewrite there
# python3.5 - python3.6: `namespace`
# python3.7+: `None`
or spec.origin in {None, "namespace"}
# we can only rewrite source files
or not isinstance(spec.loader, importlib.machinery.SourceFileLoader)
# if the file doesn't exist, we can't rewrite it
or not os.path.exists(spec.origin)
):
return None
else:
fn = spec.origin
if not self._should_rewrite(name, fn, state):
return None
return importlib.util.spec_from_file_location(
name,
fn,
loader=self,
submodule_search_locations=spec.submodule_search_locations,
)
示例11: get_suffixes
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def get_suffixes():
"""**DEPRECATED**"""
extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
return extensions + source + bytecode
示例12: load_source
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def load_source(name, pathname, file=None):
loader = _LoadSourceCompatibility(name, pathname, file)
spec = util.spec_from_file_location(name, pathname, loader=loader)
if name in sys.modules:
module = _exec(spec, sys.modules[name])
else:
module = _load(spec)
# To allow reloading to potentially work, use a non-hacked loader which
# won't rely on a now-closed file object.
module.__loader__ = machinery.SourceFileLoader(name, pathname)
module.__spec__.loader = module.__loader__
return module
示例13: load_dynamic
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def load_dynamic(name, path, file=None):
"""**DEPRECATED**
Load an extension module.
"""
import importlib.machinery
loader = importlib.machinery.ExtensionFileLoader(name, path)
# Issue #24748: Skip the sys.modules check in _load_module_shim;
# always load new extension
spec = importlib.machinery.ModuleSpec(
name=name, loader=loader, origin=path)
return _load(spec)
示例14: exec_module
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def exec_module(self, path):
"""execute plugin as an `importlib` module
"""
loader = importlib.machinery.SourceFileLoader(self.filename, path)
module = importlib.import_module(self.filename)
# If the instance is the first one, it means that
# the import already executed the plugin.
if not self.is_first_instance():
loader.exec_module(module)
示例15: find_spec
# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import machinery [as 别名]
def find_spec(self, fullname, path, target=None):
if fullname in self._MODULES:
# If being called from kaggle_gcp, don't return our
# monkeypatched module to avoid circular dependency,
# since we call kaggle_gcp to load the module.
if self._is_called_from_kaggle_gcp():
return None
return importlib.machinery.ModuleSpec(fullname, GcpModuleLoader())