[英]pressing ctrl+D doesn't give complete output
我在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后才能獲得完整輸出。 為什么會這樣? 我該如何解決?
文件對象迭代( for line in sys.stdin: ..
)執行內部緩沖會導致您觀察到的行為。
通過在while
循環中使用sys.stdin.readline()
,可以避免它。
更改以下行:
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.