我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用imp.load_compiled()。
def load_module(self, name): # If there is an existing module object named 'fullname' in # sys.modules, the loader must use that existing module. (Otherwise, # the reload() builtin will not work correctly.) if name in sys.modules: return sys.modules[name] co, pyc = self.modules.pop(name) # I wish I could just call imp.load_compiled here, but __file__ has to # be set properly. In Python 3.2+, this all would be handled correctly # by load_compiled. mod = sys.modules[name] = imp.new_module(name) try: mod.__file__ = co.co_filename # Normally, this attribute is 3.2+. mod.__cached__ = pyc mod.__loader__ = self py.builtin.exec_(co, mod.__dict__) except: del sys.modules[name] raise return sys.modules[name]
def _write_pyc(state, co, source_stat, pyc): # Technically, we don't have to have the same pyc format as # (C)Python, since these "pycs" should never be seen by builtin # import. However, there's little reason deviate, and I hope # sometime to be able to use imp.load_compiled to load them. (See # the comment in load_module above.) try: fp = open(pyc, "wb") except IOError: err = sys.exc_info()[1].errno state.trace("error writing pyc file at %s: errno=%s" %(pyc, err)) # we ignore any failure to write the cache file # there are many reasons, permission-denied, __pycache__ being a # file etc. return False try: fp.write(imp.get_magic()) mtime = int(source_stat.mtime) size = source_stat.size & 0xFFFFFFFF fp.write(struct.pack("<ll", mtime, size)) marshal.dump(co, fp) finally: fp.close() return True
def load_module(self, name, stuff): file, filename, info = stuff (suff, mode, type) = info try: if type == BUILTIN_MODULE: return self.hooks.init_builtin(name) if type == FROZEN_MODULE: return self.hooks.init_frozen(name) if type == C_EXTENSION: m = self.hooks.load_dynamic(name, filename, file) elif type == PY_SOURCE: m = self.hooks.load_source(name, filename, file) elif type == PY_COMPILED: m = self.hooks.load_compiled(name, filename, file) elif type == PKG_DIRECTORY: m = self.hooks.load_package(name, filename, file) else: raise ImportError, "Unrecognized module type (%r) for %s" % \ (type, name) finally: if file: file.close() m.__file__ = filename return m
def LoadFromFile(self, filepath, expectedClass): class_inst = None mod_name,file_ext = splitext(split(filepath)[-1]) if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) if hasattr(py_mod, expectedClass): class_inst = getattr(py_mod, expectedClass)() return class_inst # Function to be called. Simulates the game and returns the json dump
def _load_plugin_class(self, filepath): """ Loads the plugin method and sets the self.plugin to refer to it. :param filepath: path to the file containing the python function """ expected_class = 'ObservationUpdater' mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) if file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) else: py_mod = imp.load_source(mod_name, filepath) if hasattr(py_mod, expected_class): self.plugin = getattr(py_mod, expected_class)() else: raise Exception( 'Cannot find ObservationUpdater class in pluging file ' + filepath) if not hasattr(self.plugin, 'update'): raise Exception( 'Cannot find update method in plugin class ' + filepath)
def load_compiled(self, name, filename, file=None): return imp.load_compiled(name, filename, file)
def load_module_pyc(module_id, path): with open(path, 'rb') as fp: mod = imp.load_compiled(module_id, path, fp) # no source encoding here return mod
def load_from_file(self, uri): uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri)) path, fname = os.path.split(uri) mname, _ = os.path.splitext(fname) no_ext = os.path.join(path, mname) self.logger.debug("Looking for: " + no_ext) if os.path.exists(no_ext + '.pyc'): self.logger.debug("Loading compiled: " + mname + " from " + no_ext) return imp.load_compiled(mname, no_ext + '.pyc') if os.path.exists(no_ext + '.py'): self.logger.debug("Compiling: " + mname + " from " + no_ext) return imp.load_source(mname, no_ext + '.py') return None
def function_importer(mod_str): # pylint: disable=too-complex """Import Module from external source""" mod_split = mod_str.split(":") if len(mod_split) != 2: logger.error("Can not import function", mod=mod_str) return None mod_path = mod_split[0] funct_name = mod_split[1].split('.') path, filename = os.path.split(mod_path) mod_name, ext = os.path.splitext(filename) # pylint: disable=unused-variable mod = None # try to load precompiled in first if it exists if os.path.exists(os.path.join(path, mod_name)+'.pyc'): try: mod = imp.load_compiled(mod_name, mod_path) except: # pylint: disable=bare-except pass if os.path.exists(os.path.join(path, mod_name)+'.py'): try: mod = imp.load_source(mod_name, mod_path) except Exception as e: logger.error("No Class to import", mod=mod_str, error=e.message) # Pull function if embedded in classes for i, mod_part in enumerate(funct_name): if mod and hasattr(mod, mod_part): if i == len(funct_name) - 1: if len(funct_name) > 1: return getattr(mod(), mod_part) return getattr(mod, mod_part) mod = getattr(mod, mod_part) logger.error("Function not valid/callable", mod=mod_str) return None
def load_from_file(filepath): mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1]) if mod_name.startswith("__init__"): return if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) else: return None class_inst = getattr(py_mod, mod_name)() return class_inst
def import_module(filepath): class_inst = None #expected_class = 'MyClass' mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1]) assert os.path.isfile(filepath), 'File %s does not exists.' % filepath if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) return py_mod
def load_from_file(filepath, expectedClass): class_inst = None mod_name,file_ext = splitext(split(filepath)[-1]) if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) if hasattr(py_mod, expectedClass): class_inst = getattr(py_mod, expectedClass)() return class_inst
def load_module_from_file(filepath, d=None): class_inst = None expected_class = 'main' mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) if hasattr(py_mod, expected_class): class_inst = getattr(py_mod, expected_class)(d) return class_inst
def _load_plugins_from(self, path): files = sorted(os.listdir(path)) # sorting to ensure that .py goes first included = [] for f in files: if f.startswith('plugin_'): try: if f.endswith('.py'): if f + 'c' in files: if os.path.getmtime(os.path.join(path, f + 'c')) > os.path.getmtime(os.path.join(path, f)): # .pyc newer continue elif f + 'o' in files: if os.path.getmtime(os.path.join(path, f + 'o')) > os.path.getmtime(os.path.join(path, f)): # .pyo newer continue self._add_plugin( imp.load_source('', os.path.join(path, f)), f, f[7:-3]) included.append(f) elif f.endswith('.pyc') or f.endswith('.pyo'): if f[:-1] in included: continue if f.endswith('c') and f[:-1] + 'o' in files: if os.path.getmtime(os.path.join(path, f[:-1] + 'o')) > os.path.getmtime(os.path.join(path, f)): # .pyo newer continue elif f[:-1] + 'c' in files: if os.path.getmtime(os.path.join(path, f[:-1] + 'c')) > os.path.getmtime(os.path.join(path, f)): # .pyc newer continue self._add_plugin( imp.load_compiled('', os.path.join(path, f)), f, f[7:-4]) included.append(f[:-1]) except Exception: self.log(u'[b]?????? ??? ???????? ??????? %s[/b]' % f, 2) self.log(traceback.format_exc().decode('utf8'), 2)