Linux中的tee命令与Python无法配合使用?

153

我写了一个Python脚本,使用无限循环与Web服务器通信。我想将每个通信的数据记录到文件中,并同时在终端监视这些数据。因此,我使用了像这样的tee命令。

python client.py | tee logfile

然而,从终端或日志文件中我没有得到任何信息。 Python脚本正常运行。 这里发生了什么? 我有什么遗漏吗?

如果您有任何建议,将不胜感激。 提前致谢。


4
缓冲对管道和终端的行为不同。每次记录一行时,您可能需要从脚本中显式地执行 sys.stdout.flush() - Lukas Graf
有关其他触发无缓冲输出的方法,请参见https://dev59.com/inVD5IYBdhLWcg3wDHDm - Dima Chubarov
2个回答

256

来自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
另一种选择是使用 script,它也禁用缓冲,并使控制序列(C-a、光标键等)工作:https://dev59.com/UYjca4cB1Zd3GeqPqQL3#39269661。 - blueyed
太好了!它在我的树莓派3上,配备了Raspbian Jessie操作系统,同时也在Python 3中运行成功:python3 -u client.py | tee logfile - Antonino
注意:Python和其他一些命令一样,如果标准输入和输出是控制台,则使用行缓冲,但如果结果被重定向到文件或管道,则使用完全缓冲。tee被视为管道(它确实是),而不是混合体:它写入控制台。注意:这种行为也可以在Python程序内部进行控制。 - Giacomo Catenazzi
另一个注意事项:python -u client.py | tee >> logfile 不起作用。 >> 会导致文件另一种缓冲写入情况。这就是 tee -a 解决的问题。 - tanius
也可以在 shebang 行中加入 -u,它会这样工作:#!/usr/bin/python3 -u - Sergey M

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接