用编解码器读取stdin的延迟

时间:2013-06-18 14:58:09

标签: python stdin codec

我正在尝试使用下面的代码使用编解码器从stdin读取

import codecs

ins = codecs.getreader('utf-8')(sys.stdin, 'replace')
for l in ins:
    print l

我有另一个脚本在短小数据的突发中写入stdout。我需要我的脚本在每次爆发后处理数据。但是,编解码器似乎缓冲了数据。这意味着写入stdout的行不会立即显示在我上面的阅读器代码中。我可以设置一个参数来阻止缓冲吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

在这个看似简单的例子中有两个级别的缓冲。 为了避免第一级 - 更多的是作为解决方法而不是解决方案 - 你可以读取每一行然后解码它,而不是反过来。它的工作原理是因为在utf-8中,行尾仍然是不明显的。 (注意:这第一段代码不起作用,因为它仍然具有第二级缓冲!包括在内以供说明)

for l in sys.stdin:
    l = l.decode('utf-8', 'replace')
    print l

第二级来自for l in file。所以你实际上需要:

while True:
    l = sys.stdin.readline()
    if not l: break
    l = l.decode('utf-8', 'replace')
    print l