按ctrl + D不会给出完整的输出

时间:2016-03-17 06:48:21

标签: python

我在python中有以下代码:

#!/usr/bin/python

import sys

def reducer():

    oldKey = None
    totalSales = 0

    for line in sys.stdin:
            data= line.strip().split("\t")
            if(len(data)!=2):
                    continue

            thisKey,thisSale = data

            if (oldKey and oldKey != thisKey):
                    print ("{}\t{}".format(oldKey,totalSales))
                    oldKey=thisKey
                    totalSales = 0


            oldKey = thisKey
            totalSales += float(thisSale)

    if(oldKey!=None):
            print("{}\t{}".format(oldKey,totalSales))

reducer()

当我提供输入时:

a       1
a       2
a       3
b       4
b       5
b       6
c       1
c       2

并按 Ctrl + D 此处

我得到输出:

a       6.0
b       15.0

我希望输出为:

a       6.0
b       15.0
c       3.0

我再次按 Ctrl + D 后才能获得完整输出。为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:1)

文件对象迭代(for line in sys.stdin: ..)执行内部缓冲会导致您观察到的行为。

sys.stdin.readline()while循环一起使用,可以避免它。

更改以下行:

for line in sys.stdin:

使用:

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

相关的PYTHON(1)联构部分:

   -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 xread‐
          lines(), 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.readline()" inside
          a "while 1:" loop.