Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python过滤tail-in的输出_Python_Unix_Command Line - Fatal编程技术网

用Python过滤tail-in的输出

用Python过滤tail-in的输出,python,unix,command-line,Python,Unix,Command Line,一个简单的过滤脚本,看起来很像 import sys for line in sys.stdin: print line 如果tail-f的输出通过管道传输,则不打印任何内容,但与cat的输出配合良好grep与tail-f没有任何问题,因此我想我应该以某种方式更改脚本处理输入的方式。根据python(1)手册: 请注意,xreadlines()、readlines()和文件对象迭代器(“for line insys.stdin”)中有内部缓冲区,不受此选项的影响。为了解决这个问题,您需要

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

import sys

for line in sys.stdin:
  print line
如果
tail-f
的输出通过管道传输,则不打印任何内容,但与
cat
的输出配合良好<但是,code>grep与
tail-f
没有任何问题,因此我想我应该以某种方式更改脚本处理输入的方式。

根据python(1)手册:

请注意,xreadlines()、readlines()和文件对象迭代器(“for line insys.stdin”)中有内部缓冲区,不受此选项的影响。为了解决这个问题,您需要在“while1:”循环中使用“sys.stdin.readline()”

请尝试以下操作:

import sys

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