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

标签 python python-3.x

我试图将一个函数的输出存储到 Python 中的一个文件中,我想做的是这样的:

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

但是当我这样做时,我得到了这个错误:

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

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

最佳答案

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

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

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

编辑:如果你想要它作为一个字符串,使用io.StringIO:

f = io.StringIO()
with contextlib.redirect_stdout(f):
    test()
s = f.getvalue()

关于Python,将函数的输出重定向到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885878/

相关文章:

python - 包 __init__.py 中导入的模块不可通过点访问

python - 获取 TypeError : list indices must be integers, 不是元组

从流中读取多个 protobuf 消息的 python 示例

python - pandas 合并列并添加原始列

python - 即使条件尚未满足,程序也会停止

python - 与 None 变量类型的比较

python - 按 15 分钟时间间隔(但针对全天)的 pandas 数据框进行分组

python - 使用 init_model 中的模型对 Pylons 应用程序进行 Nose 测试?

python - Voronoi图的轮廓坐标

postgresql - 在 windows 7 64 位 + python 3.4 上安装 psycopg2