Get The Results Of Dis.dis() In A String
I am trying to compare the bytecode of two things with difflib, but dis.dis() always prints it to the console. Any way to get the output in a string?
Solution 1:
If you're using Python 3.4 or later, you can get that string by using the method 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
You also might want to take a look at dis.get_instructions()
, which returns an iterator of named tuples, each corresponding to a bytecode instruction.
Solution 2:
Uses StringIO to redefine std out to a string-like object (python 2.7 solution)
import sys
import StringIO
import dis
defa():
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 stdoutprint f.getvalue() # print contents
Post a Comment for "Get The Results Of Dis.dis() In A String"