如何使用importlib重写字节码?

3 投票
1 回答
620 浏览
提问于 2025-04-16 04:27

我想找一种方法,在Python 2.x中使用importlib,可以实时修改导入模块的字节码。简单来说,我需要在导入时编译和执行之间插入我自己的函数。此外,我希望这个导入功能和内置的功能一样好用。

我已经用过imputil来实现这个,但那个库并不能处理所有情况,而且已经不再维护了。

1 个回答

2

我看了一下importlib的源代码,我觉得你可以在_bootstrap模块里创建一个PyLoader的子类,并且重写get_code这个方法:

class PyLoader:
    ...

    def get_code(self, fullname):
    """Get a code object from source."""
    source_path = self.source_path(fullname)
    if source_path is None:
        message = "a source path must exist to load {0}".format(fullname)
        raise ImportError(message)
    source = self.get_data(source_path)
    # Convert to universal newlines.
    line_endings = b'\n'
    for 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)

我猜你知道自己在做什么,但我还是想代表所有程序员说一句: =p

撰写回答