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

标签 python python-3.x

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

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

>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

关于Python3.7 - 如何从字节码的代码对象中获取函数签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53318291/

相关文章:

django - 将 Django 查询对象 value() 传递到 Django Rest Framework Serializer

python - imageio-值错误: Could not find a format to read the specified file in mode 'i'

python - Distutils 安装程序在 Mac OS X 上生成 .so 而不是 .dylib

python - 什么时候使用 `<>` 和 `!=` 运算符?

mysql - 如何在Python中检测字符串中unicode的部分

python-3.x - 当我启动hadoop cluster时,集群却无法启动,并且出现了裂伤问题

python - 删除在 python3 中使用 venv 创建的虚拟环境

python - zeromq:如何防止无限等待?

python - 将数据框拆分为单独的 CSV 文件

python - 按键 : ascending and descending for every tuple of key's value 对字典列表进行复杂排序