def load_room(name, room_type='usual', user=None): path = 'rooms/{0}/{1}/{2}.py'.format(user.rooms_pack if user is not None else 'default', room_type, name) if not os.path.exists(path): path += 'c' if not os.path.exists(path): return None import_name = (room_type + '.' + name).replace('/', '.'); if path.endswith('c'): room_loader = SourcelessFileLoader(import_name, path) else: room_loader = SourceFileLoader(import_name, path) room = room_loader.load_module(import_name) return check_room(room, name, room_type)
def import_file_to_module(module_name, fpath, loader=None): """Import Hy source from fpath and put it into a Python module. If there's an up-to-date byte-compiled version of this module, load that instead. Otherwise, byte-compile the module once we're done loading it, if we can. Return the module.""" module = None bytecode_path = get_bytecode_path(fpath) try: source_mtime = int(os.stat(fpath).st_mtime) with open(bytecode_path, 'rb') as bc_f: # The first 4 bytes are the magic number for the version of Python # that compiled this bytecode. bytecode_magic = bc_f.read(4) # The next 4 bytes, interpreted as a little-endian 32-bit integer, # are the mtime of the corresponding source file. bytecode_mtime, = struct.unpack('<i', bc_f.read(4)) except (IOError, OSError): pass else: if bytecode_magic == MAGIC and bytecode_mtime >= source_mtime: # It's a cache hit. Load the byte-compiled version. if PY3: # As of Python 3.6, imp.load_compiled still exists, but it's # deprecated. So let's use SourcelessFileLoader instead. from importlib.machinery import SourcelessFileLoader module = (SourcelessFileLoader( module_name, bytecode_path).load_module(module_name)) else: module = imp.load_compiled(module_name, bytecode_path) if not module: # It's a cache miss, so load from source. sys.modules[module_name] = None try: _ast = import_file_to_ast(fpath, module_name) module = imp.new_module(module_name) module.__file__ = os.path.normpath(fpath) code = ast_compile(_ast, fpath, "exec") if not os.environ.get('PYTHONDONTWRITEBYTECODE'): try: write_code_as_pyc(fpath, code) except (IOError, OSError): # We failed to save the bytecode, probably because of a # permissions issue. The user only asked to import the # file, so don't bug them about it. pass eval(code, module.__dict__) except (HyTypeError, LexException) as e: if e.source is None: with open(fpath, 'rt') as fp: e.source = fp.read() e.filename = fpath raise except Exception: sys.modules.pop(module_name, None) raise sys.modules[module_name] = module module.__name__ = module_name module.__file__ = os.path.normpath(fpath) if loader: module.__loader__ = loader if is_package(module_name): module.__path__ = [] module.__package__ = module_name else: module.__package__ = module_name.rpartition('.')[0] return module