我写了一个Python脚本,使用无限循环与Web服务器通信。我想将每个通信的数据记录到文件中,并同时在终端监视这些数据。因此,我使用了像这样的tee命令。
python client.py | tee logfile
然而,从终端或日志文件中我没有得到任何信息。 Python脚本正常运行。 这里发生了什么? 我有什么遗漏吗?
如果您有任何建议,将不胜感激。 提前致谢。
来自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
script
,它也禁用缓冲,并使控制序列(C-a
、光标键等)工作:https://dev59.com/UYjca4cB1Zd3GeqPqQL3#39269661。 - blueyedtee
被视为管道(它确实是),而不是混合体:它写入控制台。注意:这种行为也可以在Python程序内部进行控制。 - Giacomo Catenazzipython -u client.py | tee >> logfile
不起作用。 >>
会导致文件另一种缓冲写入情况。这就是 tee -a
解决的问题。 - tanius不要将其完全设置为非缓冲模式,而是可以将其设置为行缓冲模式,通常方法是使用sys.stdout.reconfigure(line_buffering=True)
(当然,在导入sys
后)。
这项功能从3.7开始添加,文档链接:https://docs.python.org/zh-cn/3/library/io.html#io.TextIOWrapper.reconfigure
sys.stdout.flush()
。 - Lukas Graf