為sys.stdin設置較小的緩沖區大???我正在使用以下bash命令模式運行memcached:memcached -vv 2>&1 | tee memkeywatch2010098.log 2>&1 | ~/bin/memtracer.py | tee memkeywatchCounts20100908.log嘗試跟蹤無與倫比的獲取到平臺鍵的集合。memtracer腳本位于下方并按預期工作,只有一個小問題。看到中間日志文件大小,memtracer.py在memkeywatchYMD.log大小約為15-18K之前不會開始輸入。有沒有更好的方法來讀取stdin或者可能是將緩沖區大小降低到1k以下以獲得更快的響應時間?#!/usr/bin/pythonimport sysfrom collections import defaultdictif __name__ == "__main__":
keys = defaultdict(int)
GET = 1
SET = 2
CLIENT = 1
SERVER = 2
#if <
for line in sys.stdin:
key = None
components = line.strip().split(" ")
#newConn = components[0][1:3]
direction = CLIENT if components[0].startswith("<") else SERVER #if lastConn != newConn:
# lastConn = newConn
if direction == CLIENT:
command = SET if components[1] == "set" else GET
key = components[2]
if command == SET:
keys[key] -= 1
elif direction == SERVER:
command = components[1]
if command == "sending":
key = components[3]
keys[key] += 1
if key != None:
print "%s:%s" % ( key, keys[key], )
3 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
您可以使用python的-u
標志從stdin / stdout中完全刪除緩沖:
-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) see man page for details on internal buffering relating to '-u'
并且手冊頁澄清了:
-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.
除此之外,不支持更改現有文件的緩沖,但是您可以使用os.fdopen創建具有與現有文件相同的基礎文件描述符的新文件對象,并可能使用不同的緩沖。也就是說,
import osimport sys newin = os.fdopen(sys.stdin.fileno(), 'r', 100)
應該綁定newin
到一個文件對象的名稱,該文件對象讀取與標準輸入相同的FD,但一次只緩沖大約100個字節(并且您可以繼續sys.stdin = newin
使用新文件對象作為此處的標準輸入)。我說“應該”,因為這個區域過去常常在某些平臺上出現一些錯誤和問題(提供完全通用的跨平臺功能非常困難) - 我不確定它現在的狀態是什么,但是我d絕對建議在所有感興趣的平臺上進行全面測試,以確保一切順利。(-u
,完全刪除緩沖,如果可能滿足您的要求,應該在所有平臺上使用更少的問題)。
添加回答
舉報
0/150
提交
取消