4

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?

noɥʇʎԀʎzɐɹƆ
  • 8,421
  • 2
  • 44
  • 65

2 Answers2

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