How come I can't tail my log?

南楼画角 提交于 2019-12-25 04:16:04

问题


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 

Nothing shows up when I tail it.


回答1:


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

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

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

or you can use the PYTHONUNBUFFERED environment variable:

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

or re-open the stdout filehandle in unbuffered mode:

import os
import sys

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

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

print(count, flush=True)



回答2:


It's because writes to standard output are buffered by default. You will see nothing until the buffer fills up or the file descriptor is flushed or closed.



来源:https://stackoverflow.com/questions/16993397/how-come-i-cant-tail-my-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!