Get the results of dis.dis() in a string

Question:

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?

Answers:

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.

Answered By: Dan Getz

Uses StringIO to redirect stdout 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
Answered By: Wayne Treible
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.