首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >linux tee不能与python一起工作?

linux tee不能与python一起工作?
EN

Stack Overflow用户
提问于 2014-02-10 02:01:36
回答 2查看 27.4K关注 0票数 123

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

代码语言:javascript
复制
python client.py | tee logfile

但是,我从终端和日志文件中什么也没有得到。python脚本运行得很好。这是怎么回事?我是不是遗漏了什么?

如果能有一些建议,我们将不胜感激。提前谢谢你。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-10 02:21:24

来自man python

代码语言:javascript
复制
   -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.

所以你能做的是:

代码语言:javascript
复制
/usr/bin/python -u client.py >> logfile 2>&1

或者使用tee

代码语言:javascript
复制
python -u client.py | tee logfile
票数 212
EN

Stack Overflow用户

发布于 2021-07-12 12:07:33

您可以像通常使用sys.stdout.reconfigure(line_buffering=True)一样(当然是在import sys之后)将其设置为行缓冲,而不是使其完全无缓冲。

这是在3.7中添加的,文档:https://docs.python.org/3/library/io.html#io.TextIOWrapper.reconfigure

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21662783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档