B
B
brutaler2010-12-20 21:44:20
Python
brutaler, 2010-12-20 21:44:20

Function output redirection in python

How to redirect the output of a certain function to a file and then return the output behavior as it was before?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rifle, 2010-12-20
@Rifle

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]

M
MikhailEdoshin, 2010-12-20
@MikhailEdoshin

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 question

Ask a Question

731 491 924 answers to any question