我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用importlib.machinery()。
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)
def get_factory_from_template(maintype): path = os.path.join(BASE_DIR, 'templates', maintype, FACTORY_FILENAME) if (python_version_gte(3, 5)): # Python 3.5 code in this block import importlib.util spec = importlib.util.spec_from_file_location( "{}.factory".format(maintype), path) foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) return foo elif (python_version_gte(3, 0)): from importlib.machinery import SourceFileLoader foo = SourceFileLoader( "{}.factory".format(maintype), path).load_module() return foo else: # Python 2 code in this block import imp foo = imp.load_source("{}.factory".format(maintype), path) return foo
def load_user_logic(module_name): full_path = bge.logic.expandPath("//bgelogic/cells/{}.py".format(module_name)) loaded_value = _loaded_userlogic_files.get(full_path) if loaded_value: return loaded_value import sys python_version = sys.version_info major = python_version[0] minor = python_version[1] if (major < 3) or (major == 3 and minor < 3): import imp loaded_value = imp.load_source(module_name, full_path) elif (major == 3) and (minor < 5): from importlib.machinery import SourceFileLoader loaded_value = SourceFileLoader(module_name, full_path).load_module() else: import importlib.util spec = importlib.util.spec_from_file_location(module_name, full_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) loaded_value = module _loaded_userlogic_files[module_name] = loaded_value return loaded_value
def _abs_import(module_name, full_path): import sys python_version = sys.version_info major = python_version[0] minor = python_version[1] if (major < 3) or (major == 3 and minor < 3): import imp return imp.load_source(module_name, full_path) elif (major == 3) and (minor < 5): from importlib.machinery import SourceFileLoader return SourceFileLoader(module_name, full_path).load_module() else: import importlib.util spec = importlib.util.spec_from_file_location(module_name, full_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module pass
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) if verbose > 1: print(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)
def import_function(file_path, function_name): # strong assumption here that we're in a new process file_path = os.path.expanduser(file_path) sys.path.insert(0, os.path.dirname(file_path)) if hasattr(importlib, "util"): # Python 3.4+ spec = importlib.util.spec_from_file_location( "external_file", file_path) external_file = importlib.util.module_from_spec(spec) spec.loader.exec_module(external_file) elif hasattr(importlib, "machinery"): # Python 3.3 from importlib.machinery import SourceFileLoader external_file = SourceFileLoader( "external_file", file_path).load_module() else: # Python 2.x import imp external_file = imp.load_source("external_file", file_path) if not external_file: raise TuneError("Unable to import file at {}".format(file_path)) return getattr(external_file, function_name)
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)
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
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(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)
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
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
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)
def get_pathfinder_index_in_meta_hooks(): return sys.meta_path.index(importlib.machinery.PathFinder)
def importer (directory, libpath, module = None): fn = not libpath.endswith (".py") and libpath + ".py" or libpath modpath = os.path.join (directory, fn) hname = fn.split (".")[0] p = directory.replace ("\\", "/") if p.find (":") !=- 1: p = "/" + p.replace (":", "") while 1: if "skitai.mounted." + hname in sys.modules: p, l = os.path.split (p) if not l: raise SystemError ('module %s already imported, use reload') hname = l + "." + hname else: hname = "skitai.mounted." + hname break loader = importlib.machinery.SourceFileLoader(hname, modpath) mod = loader.load_module () return mod, mod.__file__
def test_dash_c_loader(self): rc, out, err = assert_python_ok("-c", "print(__loader__)") expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") self.assertIn(expected, out)
def test_stdin_loader(self): # Unfortunately, there's no way to automatically test the fully # interactive REPL, since that code path only gets executed when # stdin is an interactive tty. p = spawn_python() try: p.stdin.write(b"print(__loader__)\n") p.stdin.flush() finally: out = kill_python(p) expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8") self.assertIn(expected, out)
def test_basic_script(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') self._check_script(script_name, script_name, script_name, script_dir, None, importlib.machinery.SourceFileLoader)
def test_script_compiled(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') py_compile.compile(script_name, doraise=True) os.remove(script_name) pyc_file = support.make_legacy_pyc(script_name) self._check_script(pyc_file, pyc_file, pyc_file, script_dir, None, importlib.machinery.SourcelessFileLoader)
def test_directory(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') self._check_script(script_dir, script_name, script_dir, script_dir, '', importlib.machinery.SourceFileLoader)
def test_module_in_package(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, 'script') launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script') self._check_script(launch_name, script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader)
def test_package(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_script(launch_name, script_name, script_name, script_dir, 'test_pkg', importlib.machinery.SourceFileLoader)
def test_package_compiled(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) pyc_file = support.make_legacy_pyc(script_name) launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_script(launch_name, pyc_file, pyc_file, script_dir, 'test_pkg', importlib.machinery.SourcelessFileLoader)
def test_issue8202_dash_m_file_ignored(self): # Make sure a "-m" file in the current directory # does not alter the value of sys.path[0] with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'other') with support.change_cwd(path=script_dir): with open("-m", "w") as f: f.write("data") rc, out, err = assert_python_ok('-m', 'other', *example_args) self._check_output(script_name, rc, out, script_name, script_name, '', '', importlib.machinery.SourceFileLoader)