简体   繁体   English

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

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

I need to find out function signature from bytecode.我需要从字节码中找出函数签名。 I am trying to add inspect functionality to disassembly, but get some problem.我正在尝试将检查功能添加到反汇编中,但遇到了一些问题。

Here is the source code to be compiled to bytecode:这是要编译为字节码的源代码:

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

a=foo(x)
print(a)

Here is my modification of the dis package in Lib/dis.py:下面是我对 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)

After rebuilding Python, I get the following error in running disassembly:重建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

My immediate question is - how to get a callable from code object?我的直接问题是 - 如何从代码对象中获取可调用对象?

Maybe I am on the wrong track, the end goal is, I need to hack Python 3.7's disassembler so that I can get the signature of a function.也许我在错误的轨道上,最终目标是,我需要破解 Python 3.7 的反汇编器,以便我可以获得函数的签名。

Appreciate your help.感谢你的帮助。

This is a really bad way to get a code object's signature, but it's pretty cool to try.这是获取代码对象签名的一种非常糟糕的方法,但尝试一下非常酷。

Here's what I did:这是我所做的:

import inspect
import types

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

Hope this helps :D希望这有帮助:D

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

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