2014-01-17 312 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)