簡體   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