dis庫是python(默認(rèn)的CPython)自帶的一個(gè)庫,可以用來分析字節(jié)碼
例子
首先導(dǎo)入dis庫
>>> import dis
然后在repl中,創(chuàng)建一個(gè)函數(shù)
>>> def add(a, b = 0):
... return a + b
...
>>>
最后將add函數(shù)傳給dis庫的dis函數(shù)
>>> dis.dis(add)
2 0 LOAD_FAST 0 (a)
2 LOAD_FAST 1 (b)
4 BINARY_ADD
6 RETURN_VALUE
>>>
repl會(huì)返回add函數(shù)的字節(jié)碼.
分析
來看看dis函數(shù)的源碼
def dis(x=None, *, file=None):
"""Disassemble classes, methods, functions, generators, or code.
With no argument, disassemble 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("Disassembly 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
disassemble(x, file=file)
elif isinstance(x, (bytes, bytearray)): # Raw bytecode
_disassemble_bytes(x, file=file)
elif isinstance(x, str): # Source code
_disassemble_str(x, file=file)
else:
raise TypeError("don't know how to disassemble %s objects" %
type(x).__name__)
x參數(shù)可以是None朴恳、Method、Function陪毡、Generator、Class秸应、module、Code object、Raw bytecode摩瞎、Source code,如果x是Method纹笼、Function纹份、Generator,只用返回對應(yīng)的字節(jié)碼,
如果x是Class或者module,那會(huì)返回x的所有元素(先排序)的字節(jié)碼,這一句代碼x.dict.items()有提現(xiàn).如果x是Code object或者Raw bytecode,或者Source code,那么會(huì)調(diào)用對應(yīng)的disassemble函數(shù). disassemble函數(shù)是干嘛的呢,顧名思義,就是assemble的反義詞, assemble是匯編的意思,那disassemble自然是有一個(gè) 反匯編 的意思,當(dāng)然這里并不是真的反匯編,而是只是輸出字節(jié)碼.
disassemble的函數(shù)細(xì)節(jié)可以自己去看看源碼,源碼也在dis.py里