Python,将函数的输出重定向到文件中

Sau*_*lis 3 python python-3.x

我正在尝试将函数的输出存储到Python中的文件中,我想要做的是这样的:

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

但是,当我这样做时,我收到此错误:

TypeError:参数1必须是字符串或只读字符缓冲区,而不是None

PD:我正在尝试为我无法修改的功能执行此操作.

o11*_*11c 8

每当需要成对执行任何操作时,请使用上下文管理器.

在这种情况下,使用contextlib.redirect_stdout:

with open('Log','a') as f:
    with contextlib.redirect_stdout(f):
        test()
Run Code Online (Sandbox Code Playgroud)

编辑:如果您想将其作为字符串,请使用io.StringIO:

f = io.StringIO()
with contextlib.redirect_stdout(f):
    test()
s = f.getvalue()
Run Code Online (Sandbox Code Playgroud)