为什么我不能拖尾我的日志?

TIM*_*MEX 0 python linux ubuntu logging

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

count = 0
while 1:
    print count
    count += 1
Run Code Online (Sandbox Code Playgroud)

我保存了这个文件并运行了它.

nohup python count.py >> test.log &

$tail -f test.log 
Run Code Online (Sandbox Code Playgroud)

我拖尾时什么都没有出现.

Mar*_*ers 8

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

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

import sys

count = 0
while 1:
    print count
    sys.stdout.flush()
    count += 1
Run Code Online (Sandbox Code Playgroud)

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

nohup python -u count.py >> test.log &
Run Code Online (Sandbox Code Playgroud)

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

PYTHONUNBUFFERED=1 nohup python count.py >> test.log &
Run Code Online (Sandbox Code Playgroud)

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

import os
import sys

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Run Code Online (Sandbox Code Playgroud)

在Python 3.3及更高版本中,这有点简单; 你只需告诉print()冲洗:

print(count, flush=True)
Run Code Online (Sandbox Code Playgroud)