繁体   English   中英

如何立即打印出Python消息到linux stdout

[英]How to print out Python message to linux stdout immediately

通常我想在linux中运行我的python代码,如下所示:

nohup python test.py > nohup.txt 2>&1 &

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

你可以在stdout上调用flush 如果在print调用后调整代码以刷新缓冲区是可行且实用的,则在test.py

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文件并查看实时打印的消息。

只需确保安装了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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM