Windows 仅在进程停止后写入文件

Windows only writes to file after process is stopped

我写了一个非常简单的脚本来测试 windows 机器 stdout 的重定向。程序是这样的

# hw.py
def main():
    print('Hello World')
    import time
    time.sleep(1000)

if __name__ == '__main__':
    main()

我运行这个脚本使用下面的命令。

python3 hw.py > hw.log

通过实时观察 hw.log 在 git bash 上使用 tail -f 或打开 emacs 缓冲区,我注意到 'Hello World' 仅在进程结束或过早取消时打印到 hw.log


这意味着我无法在将程序输出写入文件时实时查看程序输出。 更糟糕的是,如果我的程序包含无限子进程,程序的任何输出都不会写入文件

我该如何解决这个问题?

要强制 Python stdout 和 stderr 流无缓冲,您可以传递 -u 参数。

python3 -u hw.py > hw.log

设置环境变量PYTHONBUFFERRED=1效果一样