我想知道如何修改字节码,然后重新编译该代码,以便我可以在python中使用它作为一个函数?我一直在努力:
a = """
def fact():
a = 8
a = 0
"""
c = compile(a, '<string>', 'exec')
w = c.co_consts[0].co_code
dis(w)
Run Code Online (Sandbox Code Playgroud)
反编译为:
0 LOAD_CONST 1 (1)
3 STORE_FAST 1 (1)
6 LOAD_CONST 2 (2)
9 STORE_FAST 1 (1)
12 LOAD_CONST 0 (0)
15 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
假设我想摆脱第0和第3行,我打电话给:
x = c.co_consts[0].co_code[6:16]
dis(x)
Run Code Online (Sandbox Code Playgroud)
这导致:
0 LOAD_CONST 2 (2)
3 STORE_FAST 1 (1)
6 LOAD_CONST 0 (0)
9 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
我的问题是如何处理x,如果我尝试exec x我得到一个'没有nullbytes的预期字符串,我得到相同的exec w,尝试编译x结果:compile()期望字符串没有空字节.
我不知道最好的方法是什么,除了我可能需要创建某种代码对象,但我不知道如何,但我认为它必须是可能的字节游戏,python汇编程序等
我正在使用python 2.7.10,但如果可能的话,我希望将来兼容(例如python 3).
我正在查看 codetype 对象,特别是 co_flags 属性。
我写了一个小函数
def f(a,b,c,*args):
print a,b,c,args
Run Code Online (Sandbox Code Playgroud)
它被编译为代码类型对象。检查codetype对象,容器(外部codetype)co_flag设置为64,函数(内部codetype)为71
根据文档,如果函数具有变量参数(例如 *args)并且该位在外部和内部代码类型对象上设置,则设置 0x40 (64)。
我是在想
是否有文档提到“保留供内部使用”但没有提及其他内容的各种标志的完整列表?
我正在使用 python 2.7.10