Python标准库中的dis模块通过将其分解为易于理解的形式,提供了各种功能,可用于分析Python字节码。这有助于执行优化。字节码是解释器的特定于版本的实现细节。
dis()函数
该函数dis() 生成任何Python代码源的反汇编表示,即模块,类,方法,函数或代码对象。>>> def hello():
print ("hello world")
>>> import dis
>>> dis.dis(hello)
2 0 LOAD_GLOBAL 0 (print)
3 LOAD_CONST 1 ('hello world')
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
字节码分析API在Bytecode类中定义。它的构造函数返回Bytecode对象,该对象具有以下方法来分析字节码
字节码()
这是构造函数。分析与函数,生成器,方法,源代码字符串或代码对象相对应的字节码。这是许多功能的便捷包装>>> string=dis.Bytecode(hello)
>>> for x in string:
print (x)
Instruction(opname = 'LOAD_GLOBAL', opcode = 116, arg = 0, argval = 'print', argrepr = 'print&