Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Redirect output of a Function into a File

I'm trying to store the output of a Function into a file in Python, what I am trying to do is something like this:

def test():
        print("This is a Test")
file=open('Log','a')
file.write(test())
file.close()

But when I do this I get this error:

TypeError: argument 1 must be string or read-only character buffer, not None

PD: I'm trying to do this for a function I can't modify.

like image 634
Saul Solis Avatar asked Dec 03 '22 21:12

Saul Solis


1 Answers

Whenever any operation would need to be performed in pairs, use a context manager.

In this case, use contextlib.redirect_stdout:

with open('Log','a') as f:
    with contextlib.redirect_stdout(f):
        test()

Edit: if you want it as a string, use io.StringIO:

f = io.StringIO()
with contextlib.redirect_stdout(f):
    test()
s = f.getvalue()
like image 72
o11c Avatar answered Dec 06 '22 09:12

o11c