我制作了一个python脚本,它使用无限循环与Web服务器通信。 我想将每个通信数据记录到一个文件中,并同时从终端监视它们。所以我用这样的tee命令。
python client.py | tee logfile
然而,我从终端或日志文件中得不到任何东西。 python脚本工作正常。 这里发生了什么? 我错过了什么吗?
一些建议将不胜感激。 提前谢谢你。
答案 0 :(得分:140)
来自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.read‐
line()" inside a "while 1:" loop.
所以你可以做的是:
/usr/bin/python -u client.py >> logfile 2>&1
或使用tee
:
python -u client.py | tee logfile
答案 1 :(得分:1)
您可以像通常使用 sys.stdout.reconfigure(line_buffering=True)
一样(当然在 import sys
之后)那样将其设置为行缓冲,而不是完全无缓冲。
这是在 3.7 中添加的,文档:https://docs.python.org/3/library/io.html#io.TextIOWrapper.reconfigure