我怎么不能尾随日志? [英] How come I can't tail my log?

查看:75
本文介绍了我怎么不能尾随日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的python脚本中,我有这个:

In my python script, I have this:

count = 0
while 1:
    print count
    count += 1

我保存了该文件并运行.

I saved this file and I ran it.

nohup python count.py >> test.log &

$tail -f test.log 

我拖尾没什么.

推荐答案

重定向Python输出时,stdout流以缓冲模式(而不是行缓冲模式)打开.这意味着在刷新缓冲区之前,输出将一直保留在内存中,直到打印了足够的行为止.

When you redirect Python output, the stdout stream is opened in buffered mode (instead of line-buffered mode). This means that output is kept in memory until enough lines have been printed before flushing the buffer.

要立即查看行,您需要刷新输出流:

To see lines immediately, you need to flush the output stream:

import sys

count = 0
while 1:
    print count
    sys.stdout.flush()
    count += 1

或者,使用-u命令行开关强制执行无缓冲的I/O:

Alternatively, use the -u command line switch to force unbuffered I/O:

nohup python -u count.py >> test.log &

,或者您可以使用PYTHONUNBUFFERED环境变量:

or you can use the PYTHONUNBUFFERED environment variable:

PYTHONUNBUFFERED=1 nohup python count.py >> test.log &

或以无缓冲模式重新打开stdout文件句柄:

or re-open the stdout filehandle in unbuffered mode:

import os
import sys

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

在Python 3.3及更高版本中,这都更加简单.您只需告诉print()刷新:

In Python 3.3 and up this is all a little simpler; you simply tell print() to flush:

print(count, flush=True)

这篇关于我怎么不能尾随日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆