pythondis功能_python中dis的⽤法dis库是python(默认的CPython)⾃带的⼀个库,可以⽤来分析字节码
例⼦
⾸先导⼊dis库
>>> import dis
除了英语然后在repl中,创建⼀个函数
>>> def add(a, b = 0):
... return a + b
...
>>>
最后将add函数传给dis库的dis函数
>>> dis.dis(add)
2 0 LOAD_FAST 0 (a)
2 LOAD_FAST 1 (b)
4 BINARY_ADD
6 RETURN_VALUE
>>>
repl会返回add函数的字节码.
报关报检分析
来看看dis函数的源码
def dis(x=None, *, file=None):
"""Disasmble class, methods, functions, generators, or code.
With no argument, disasmble the last traceback.
鹦鹉学说话"""
if x is None:
distb(file=file)
return
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if hasattr(x, '__dict__'): # Class or module
items = sorted(x.__dict__.items())
充气南瓜饼
for name, x1 in items:
if isinstance(x1, _have_code):
print("Disasmbly of %s:" % name, file=file)
try:
dis(x1, file=file)
except TypeError as msg:
print("Sorry:", msg, file=file)
print(file=file)
elif hasattr(x, 'co_code'): # Code object
disasmble(x, file=file)
少数名族集体备课记录表
elif isinstance(x, (bytes, bytearray)): # Raw bytecode
_disasmble_bytes(x, file=file)
elif isinstance(x, str): # Source code
_disasmble_str(x, file=file)
el:
苏建城rai TypeError("don't know how to disasmble %s objects" %
type(x).__name__)
x参数可以是None、Method、Function、Generator、Class、module、Code object、Raw bytecode、Source code,如果x是Method、Function、Generator,只⽤返回对应的字节码,
如果x是Class或者module,那会返回x的所有元素(先排序)的字节码,这⼀句代码x.dict.items()有提现.如果x是Code object或者Raw bytecode,或者Source code,那么会调⽤对应的disasmble函数. disasmble函数是⼲嘛的呢,顾名思义,就是asmble的反义词, asmble是汇编的意思,那disasmble⾃然是有⼀个 反汇编 的意思,当然这⾥并不是真的反汇编,⽽是只是输出字节码.
摄影入门
disasmble的函数细节可以⾃⼰去看看源码,源码也在dis.py⾥
源码