2015-07-10 24 views
2

我試圖用difflib比較兩個事物的字節碼,但dis.dis()總是將它打印到控制檯。任何方式來獲得輸出的字符串?在字符串中獲取dis.dis()的結果

+0

@DanGetz編輯的問題。 –

+0

如果有人來到這裏並且正在尋找Python 2解決方案,請參見[this other question](http://stackoverflow.com/q/12111717/3004881)。 –

回答

2

用途StringIO的重新定義的std出到繩狀對象(蟒2.7溶液)

import sys 
import StringIO 
import dis 

def a(): 
    print "Hello World" 

stdout = sys.stdout # Hold onto the stdout handle 
f = StringIO.StringIO() 
sys.stdout = f # Assign new stdout 

dis.dis(a) # Run dis.dis() 

sys.stdout = stdout # Reattach stdout 

print f.getvalue() # print contents 
+0

我喜歡這個。它是動態的。 –

2

如果你正在使用Python 3.4或更高版本,可以使用該方法Bytecode.dis()獲得該字符串:

>>> s = dis.Bytecode(lambda x: x + 1).dis() 
>>> print(s) 
    1   0 LOAD_FAST    0 (x) 
       3 LOAD_CONST    1 (1) 
       6 BINARY_ADD 
       7 RETURN_VALUE 

你可能也想看看dis.get_instructions(),它返回一個名爲元組的迭代器每個對應一個字節碼指令。

相關問題