python - 使用Python过滤tail的输出

标签 python unix command-line

一个看起来很像的简单过滤脚本

import sys

for line in sys.stdin:
  print line

如果 tail -f 的输出通过管道传输,则不会打印任何内容,但与 cat 的输出一起工作正常。 grep 然而,tail -f 没有问题,所以我想我应该以某种方式改变脚本处理输入的方式。

最佳答案

根据 python(1) 手册页:

Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line insys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

请尝试以下操作:

import sys

while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line)
    sys.stdout.flush()

关于python - 使用Python过滤tail的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18656436/

相关文章:

bash - 如何拆分字符串取决于其他列中的模式(UNIX 环境)

unix - 替换 sed 不更改文件

c - 命令行选项创建文件的方式

c++ - 运行外部 .exe 并从中接收返回值

matlab - 如何在没有 GUI 的情况下以批处理模式运行 Matlab

python - Django 静态文件导致 404

python - “float”对象不能解释为 int,但转换为 int 不会产生任何输出

mysql - 错误 1193 (HY000) : Unknown system variable 'userstat'

python - sympy 表达式数组到 numpy 数组

python - 如何通过键连接两个RDD?