Redirecting output functions in python

0 like 0 dislike
3 views
How to redirect the output of a specific function in a file, and then return the behavior of the output as it was before?
by | 3 views

3 Answers

0 like 0 dislike
You can make a decorator, like this:
\r
import sys
\r
def decorator(n):
def out_changer(f):
sys.stdout = open(n,"w+")
def res_func(*args, **kwargs):
return f(*args, **kwargs)
return res_func
return out_changer
\r
@decorator('testfile.txt')
def your_func(a):
for i in range(a):
print i
\r
func(10)
by
0 like 0 dislike
import sys, cStringIO, traceback
\r
def capture(func, *args, **kwargs):
"""Capture the output of func when called with the given arguments.
\r
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())
\r
With the aid of capture it is easy to grab the disassembled code:
\r
import dis
\r
def disassemble(obj=None):
"""Capture the output of dis.dis and return it."""
return capture(dis.dis, obj)[1]
\r
by
0 like 0 dislike
Replace sys.stdout to a file or other object that supports the same operations (StringIO ), and then recover.
by

Related questions

0 like 0 dislike
3 answers
asked May 20, 2019 by Igorgro
0 like 0 dislike
2 answers
0 like 0 dislike
6 answers
asked Apr 1, 2019 by Slavka_online
0 like 0 dislike
6 answers
asked Apr 1, 2019 by Slavka_online
0 like 0 dislike
3 answers
110,608 questions
257,186 answers
0 comments
28,758 users