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?
Asked
Active
Viewed 812 times
4
-
@DanGetz Edited question. – noɥʇʎԀʎzɐɹƆ Jul 10 '15 at 17:51
-
If anyone gets here and is looking for a Python 2 solution, see [this other question](http://stackoverflow.com/q/12111717/3004881). – Dan Getz Jul 10 '15 at 18:02
2 Answers
4
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.
Dan Getz
- 8,122
- 6
- 30
- 61
3
Uses StringIO to redefine std out to a string-like object (python 2.7 solution)
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
Wayne Treible
- 130
- 6