问题:linux tee不能与python一起使用?

我制作了一个python脚本,该脚本使用无限循环与Web服务器通信。我想将每个通讯数据记录到一个文件中,并同时从终端监视它们。所以我像这样使用tee命令。

python client.py | tee logfile

但是,我没有从终端或日志文件中得到任何东西。python脚本运行正常。这是怎么回事 我错过了什么吗?

一些建议,将不胜感激。先感谢您。

I made a python script which communicates with a web server using an infinite loop. I want to log every communication data to a file and also monitor them from terminal at same time. so I used tee command like this.

python client.py | tee logfile

however, I got nothing from terminal nor logfile. the python script is working fine. what is happening here? am I missing something?

some advice would be appreciated. thank you in advance.


回答 0

来自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

From 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.

So what you can do is:

/usr/bin/python -u client.py >> logfile 2>&1

Or using tee:

python -u client.py | tee logfile

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。