Python在运行时自动将stdout和stderr刷新到本地文本文件

问题描述 投票:0回答:1

我有一个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安全关闭时才会被修改。

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

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

python stdout stderr file-writing
1个回答
1
投票

将文件的buffersize设置为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")

还有用的是使用print with flush关键字

print("foobar", flush=True)

但如果你不能修改print-statements,则不能使用后者

© www.soinside.com 2019 - 2024. All rights reserved.