[英]How to read most recent line from stdin in python
有沒有辦法從stdin只讀取當前數據?
我想將一些永無止境的輸入數據(從類似設備的鼠標)輸入到python腳本中,並只獲取最新的數據行。
輸入x,y數據看起來像這樣,每秒達到600行:
0.123,0.123
0.244,0.566
etc.
到目前為止,我嘗試過這樣的事情:
import sys, time
while 1:
data = sys.stdin.readline()
my_slow_function(data)
Python似乎緩沖了數據,因此沒有任何內容被跳過。 我想跳過除當前行之外的所有內容。
只需啟動一個單獨的線程,將stdin讀入全局變量。 使它成為一個守護程序線程,以便您以后不必關閉它。 線程在數據到達時讀取數據並不斷丟棄舊數據。 讓你的常規程序在想要的時候讀取last_line。
我添加了一個事件,以便常規程序可以在沒有新數據時等待。 如果那不是你想要的,那就拿出來吧。
import sys
import threading
last_line = ''
new_line_event = threading.Event()
def keep_last_line():
global last_line, new_line_event
for line in sys.stdin:
last_line = line
new_line_event.set()
keep_last_line_thread = threading.Thread(target=keep_last_line)
keep_last_line_thread.daemon = True
keep_last_line_thread.start()
保持當前行,僅作用於最后一行。
buffer = None
for line in sys.stdin:
buffer = line
my_slow_function(buffer)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.