如何使用importlib重写字节码?

发布于 2024-09-24 07:44:27 字数 244 浏览 5 评论 0原文

我正在寻找一种在 Python 2.x 中使用 importlib 重写导入的字节码的方法即时模块。换句话说,我需要在导入期间在编译和执行步骤之间挂钩我自己的函数。除此之外,我希望导入功能能够像内置功能一样工作。

我已经使用 imputil 做到了这一点,但该库并未涵盖所有情况,并且无论如何已被弃用。

I'm looking for a way to use importlib in Python 2.x to rewrite bytecode of imported modules on-the-fly. In other words, I need to hook my own function between the compilation and execution step during import. Besides that I want the import function to work just as the built-in one.

I've already did that with imputil, but that library doesn't cover all cases and is deprecated anyway.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁人与我共长歌 2024-10-01 07:44:27

查看了 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

Having had a look through the importlib source code, I believe you could subclass PyLoader in the _bootstrap module and override 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)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文