Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
import sys, cStringIO, traceback
def capture(func, *args, **kwargs):
"""Capture the output of func when called with the given arguments.
The function output includes any exception raised. capture returns
a tuple of (function result, standard output, standard error).
"""
stdout, stderr = sys.stdout, sys.stderr
sys.stdout = c1 = cStringIO.StringIO()
sys.stderr = c2 = cStringIO.StringIO()
result = None
try:
result = func(*args, **kwargs)
except:
traceback.print_exc()
sys.stdout = stdout
sys.stderr = stderr
return (result, c1.getvalue(), c2.getvalue())
With the aid of capture it is easy to grab the disassembled code:
import dis
def disassemble(obj=None):
"""Capture the output of dis.dis and return it."""
return capture(dis.dis, obj)[1]
Replace sys.stdout with a file or other object that supports the same operations ( StringIO is fine), then restore.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question