noɥʇʎԀʎzɐɹƆ
noɥʇʎԀʎzɐɹƆ

Reputation: 10657

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?

Upvotes: 5

Views: 1219

Answers (2)

Wayne Treible
Wayne Treible

Reputation: 153

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

Upvotes: 4

Dan Getz
Dan Getz

Reputation: 9152

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.

Upvotes: 6

Related Questions