2014-01-17 310 views
0

這可能是一個nooby的問題,但我找不到辦法做到這一點! 我需要清除python中的stdin緩衝區。Python:清除標準輸入緩衝區

想象我有以下bash腳本運行:從像這樣的命令行

i=0 
for ((; ;)) 
do 
    echo "$i" 
    ((i++)) 
done 

運行:./loop.sh |蟒蛇在myProg.py myProg.py

我希望擁有的東西如下:

count = 100 
f = fileinput.input() 
while True: 
    sleep(2) 
    # clear stdin somehow ... 
    # and read the most recent 100 lines 
    i = 0 
    while i < count: 
     myBuffer[i] = f.readline() 
     if len(myBuffer[i]) > 0: 
      i += 1 
    print myBuffer 

我不認爲我可以讀取所有的線,之前它,因爲它是在吐出來高速率,如果睡眠(僅用於測試atm)是幾分鐘似乎很愚蠢......有沒有一種方法來設置標準輸入緩衝區大小在python中?或者只是截斷/清除它? BTW即時通訊使用python 2所以沒有BUFSIZE參數

我看看這裏How to avoid Python fileinput buffering

做的任何蟒蛇呢?但生病嘗試無緩衝太:https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe

更新: 與非緩衝或stdbuf沒有運氣...

回答

0

以防萬一任何人有這個問題,我一直在廣泛的搜索和得出的結論是不可能由於內核實現等...

我寫了下面的工作來做我想做的事。我創建了兩個文件:textFilter.py和getLatest.py。基本上你運行./loopPrinting.sh | python textFilter.py並獲取最新的100行。我相當肯定這是原子和可靠的(但如果不是,請告訴我!!!)。它創建16個文件並更改計數(類似於我認爲的蘋果直播流)。

textFilter.py

import sys 
import os 
import time 

def mainLoop(size): 
    myBuffer = [0]*size 
    count = 0 

    while True: 
     for i in range(size): 
      myBuffer[i] = sys.stdin.readline() 

     f = open('/home/development/textFilter/' + repr(count) + '.dat', 'w') 
     f.write(''.join(myBuffer)) 
     f.close() 

     f = open('/home/development/textFilter/count.dat~', 'w') 
     f.write(repr(count)) 
     f.flush() 
     os.fsync(f.fileno()) 
     f.close() 
     time.sleep(0.01) 
     os.rename('/home/development/textFilter/count.dat~','/home/development/textFilter/count.dat') 

     count += 1 
     count = count % 16 

if __name__ == "__main__": 
    try: 
     mainLoop(int(sys.argv[1])) 
    except Exception: 
     mainLoop(100) 

getLatest.py

import sys 
import time 

def getData(): 
    f = open('count.dat', 'r') 
    count = f.read() 
    f.close() 

    count = int(count) 
    oldCount = count 

    while oldCount == count: 
    time.sleep(0.1) 
    f = open('count.dat', 'r') 
    count = f.read() 
    f.close() 
    count = int(count) 

    f = open(repr(count) + '.dat', 'r') 
    data = f.readlines() 
    f.close() 

    for row in data: 
    print row, 

    return 0 

if __name__ == "__main__": 
    try: 
    getData() 
    except Exception as inst: 
    sys.stderr.write('ERROR') 
    sys.stderr.write(inst)