按下ctrl + D不會給出完整輸出

2024-09-26 22:13:43 发布

您现在位置: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之后,我才能得到完整的输出。为什么会这样?我该怎么修?你知道吗


Tags: 代码noneformatdataifusrsysline
1条回答
网友
1楼 · 发布于 2024-09-26 22:13:43

文件对象迭代(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.

相关问题 更多 >

    热门问题