1、运行时加-u参数,如 # python3 -u test.py >> test.log &
用man查看python的-u参数,说明如下:
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators (“for line in sys.stdin”) which is not influenced by this option. To work around this, you will want to use “sys.stdin.readline()” inside a “while 1:” loop.
强制stdin,stdout和stderr完全不缓冲。
2、在不要缓冲的每一次print后面添加sys.stdout.flush()函数
3、脚本头部添加-u,如#!/usr/local/bin/python -u,道理同方法1
4、添加环境变量 PYTHONUNBUFFERED=1