如何立即将Python消息打印到Linux标准输出

3
通常我会像以下这样在Linux中运行Python代码:
nohup python test.py > nohup.txt 2>&1 &

在test.py文件中,我经常使用print命令将一些消息打印到标准输出(stdout)。但实际上,我必须等待很长时间才能看到这些消息被打印到nohup.txt文件中。如何使其快速打印出来?

你能否在你的测试程序中插入对flush的调用? - tijko
你能发布一些你的代码吗? - Will
2个回答

3

您可以在stdout上调用flush。如果您可以调整您的代码,在test.py中在print调用后刷新缓冲区,这是可行和实用的:

from sys import stdout
from time import sleep

def log():
    while True:
        print('Test log message')
        # flush your buffer
        stdout.flush()
        sleep(1)

运行此日志记录测试时,您可以检查nohup.txt文件并实时查看打印出的消息。


3

请确保您已安装 coreutils

stdbuf -oL nohup python test.py > nohup.txt 2>&1 &

这只是将缓冲设置为关闭,以便在运行此命令时可以立即看到输出。

(您可能需要在 stdbuf 前面加上 nohup ... 我不确定确切的方法)

或者...只需将以下内容放置在 test.py 的顶部:

import sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接