python - How to use importlib for rewriting bytecode? -


i'm looking way use importlib in python 2.x rewrite bytecode of imported modules on-the-fly. in other words, need hook own function between compilation , execution step during import. besides want import function work built-in one.

i've did imputil, library doesn't cover cases , deprecated anyway.

having had through importlib source code, believe subclass pyloader in _bootstrap module , override get_code:

class pyloader:     ...      def get_code(self, fullname):     """get code object source."""     source_path = self.source_path(fullname)     if source_path none:         message = "a source path must exist load {0}".format(fullname)         raise importerror(message)     source = self.get_data(source_path)     # convert universal newlines.     line_endings = b'\n'     index, c in enumerate(source):         if c == ord(b'\n'):             break         elif c == ord(b'\r'):             line_endings = b'\r'             try:                 if source[index+1] == ord(b'\n'):                     line_endings += b'\n'             except indexerror:                 pass             break     if line_endings != b'\n':         source = source.replace(line_endings, b'\n')      # modified here     code = compile(source, source_path, 'exec', dont_inherit=true)     return rewrite_code(code) 

i assume know you're doing, on behalf of programmers everywhere believe should say: ugh =p


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -