Python: 清除stdin Buffer

问题描述 投票:0回答:1

python myProg.py

in myProg.py i wish to have something as follows:

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

i don't think i can just read all the lines, before it because it is spitting them out at a high rate and if sleep (just for testing atm) is a few minutes it seems silly ... is there a way to set the stdin buffer size in python? Or just truncate

想象一下,我有以下bash脚本运行。

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

从命令行运行,如下: .loop.sh 清空它?顺便说一下,我使用的是python 2,所以没有bufsize参数。

我看了一下这里 python textFilter.py and get the Latest 100 lines. I am reasonably sure this is atomic and reliable (though if it isn't please tell me!!!). It creates 16 files and changes the count (similar to the apple live streaming i think).

textFilter.pygetLatest.py

有什么python的方法吗?但我也会尝试unbuffer。

https:/unix.stackexchange.comquestions25372turn -off -buffering-in-pipe
python file-io buffer stdin
1个回答
0
投票

这个问题可能是个新手问题,但我找不到办法!我需要在python中清除stdin缓冲区。我需要在python中清除stdin缓冲区。想象一下,我有以下bash脚本运行: i=0 for (( ; ; )) do echo "$i" ((i+...)

以防有人遇到这个问题,我已经进行了广泛的搜索,并得出结论,由于内核实现等原因,这是不可能的。

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)

我写了下面的工作方法来实现我想要的。我创建了两个文件:textFilter.py和getLatest.py。基本上你运行.loopPrinting.sh。

© www.soinside.com 2019 - 2024. All rights reserved.