函數.__ code__屬性返回封裝虛擬機字節碼的對象。
def f(): return 3
print(dir(f.__code__))
print(f.__code__.co_code) # raw compiled bytecode
訪問信息的另一種方法是顯式編譯一個文件。 這裏是一個文件test.py
:
def f(): return 3
然後,您可以鍵入蟒蛇提示:
>>> c = compile('test.py', 'test.py', 'exec')
>>> print(c.co_code) # here is some bytecode
一個簡單而有趣的方式來訪問字節碼,在一個非常清晰的方式,是運行它在終端(這裏,是dis
拆裝):
python -m dis test.py
,其輸出:
1 0 LOAD_CONST 0 (<code object f at 0x7fe8a5902300, file "p.py", line 1>)
3 LOAD_CONST 1 ('f')
6 MAKE_FUNCTION 0
9 STORE_NAME 0 (f)
12 LOAD_CONST 2 (None)
15 RETURN_VALUE
該字節碼不依賴於平臺。虛擬機是。
關於在字節碼可能的變化,我已經採取this file,並拆卸了兩遍:
python3 -m dis file.py > test1
python3 -m dis file.py > test2
然後一個簡單的差異表明:
89c89
< 26 204 LOAD_CONST 13 (<code object search_concept at 0x7f40de337300, file "powergrasp/compression.py", line 26>)
---
> 26 204 LOAD_CONST 13 (<code object search_concept at 0x7fd8de5ab300, file "powergrasp/compression.py", line 26>)
104c104
< 240 LOAD_CONST 19 (<code object compress_lp_graph at 0x7f40de340780, file "powergrasp/compression.py", line 55>)
---
> 240 LOAD_CONST 19 (<code object compress_lp_graph at 0x7fd8de5b4780, file "powergrasp/compression.py", line 55>)
的變化主要是關於進口,其中加載模塊的地址在編譯過程中不相同。
我認爲它可能會隨着解釋器版本而改變 – wRAR