繁体   English   中英

Python3.7 - 如何从字节码的代码对象中获取函数签名?

[英]Python3.7 - How to get function signature from the bytecode's code object?

我需要从字节码中找出函数签名。 我正在尝试将检查功能添加到反汇编中,但遇到了一些问题。

这是要编译为字节码的源代码:

>cat ~/tmp/func.py 
x=100
def foo(n):
    m = 10
    return n + m

a=foo(x)
print(a)

下面是我对 Lib/dis.py 中的 dis 包的修改:

import inspect   **<== my edit**
def _disassemble_recursive(co, *, file=None, depth=None):
    if depth is None or depth > 0:
        if depth is not None:
            depth = depth - 1 
        for x in co.co_consts:
            if hasattr(x, 'co_code'):
                print(file=file)
                print("Disassembly of function ", x.co_name, x)   **<== my edit**
                sig = inspect.signature(x)
                _disassemble_recursive(x, file=file, depth=depth)

重建Python后,在运行反汇编时出现以下错误:

>python3.7 -m dis ~/tmp/func.py

TypeError: <code object foo at 0x7fd594354ac0, file "~/tmp/func.py", line 2> is not a callable object

我的直接问题是 - 如何从代码对象中获取可调用对象?

也许我在错误的轨道上,最终目标是,我需要破解 Python 3.7 的反汇编器,以便我可以获得函数的签名。

感谢你的帮助。

这是获取代码对象签名的一种非常糟糕的方法,但尝试一下非常酷。

这是我所做的:

import inspect
import types

def sig_from_code(code: types.CodeType):
    return inspect.signature(
        types.FunctionType(code, {})
    )

希望这有帮助:D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM