【问题标题】:Python auto-flush stdout and stderr to local text file at runtimePython 在运行时自动刷新标准输出和标准错误到本地文本文件
【发布时间】:2019-09-14 06:57:52
【问题描述】:

我有一个 Python 脚本来持续监控各种传感器。我的 Python 脚本定期使用 print() 语句。

我的目标是让我的 Python 脚本实时发送 stdoutstderr 到一个文件。

我目前的解决方案基于以下两个答案:

这是我当前的代码:

from contextlib import redirect_stdout, redirect_stderr
from os.path import join
from some_other_package import get_base_logging_path  # returns filepath (str)

def main():
    stdout_log_path = join(get_base_logging_path(), "stdout.txt")
    stderr_log_path = join(get_base_logging_path(), "stderr.txt")
    with open(stdout_log_path, 'w') as f1, redirect_stdout(f1), \
        open(stderr_log_path, 'w') as f2, redirect_stderr(f2):
            do_stuff()

这里是我来到 Stack Overflow 的地方:文件 stdout.txtstderr.txt 仅在脚本出错或我使用 control-C 安全关闭它时才被修改。

我希望(尤其是 stdout.txt)在我的 Python 代码中每次执行新的 print() 语句时更新。如何让我的程序自动刷新 stdoutstderr 到文本文件?

注意:我试过python -u,但它似乎不起作用。

【问题讨论】:

    标签: python stdout stderr file-writing


    【解决方案1】:

    将文件的缓冲区大小设置为 1 对我有用

    from contextlib import redirect_stdout
    import time
    import sys
    
    with open("foo.txt", "w", buffering=1) as handle:
        with redirect_stdout(handle):
            print("foo")
            time.sleep(30)
            print("bar")
    

    同样有效的方法是使用带有 flush 关键字的 print

    print("foobar", flush=True)
    

    但如果您无法修改打印语句,则可能无法使用后者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2018-07-27
      • 2021-06-25
      • 1970-01-01
      相关资源
      最近更新 更多