簡體   English   中英

python中的刷新和readline的詳細信息

[英]detail of flush and readline in python

運行log.py befure follow.py它的工作原理,就像tail -f ,但運行follow.py之前log.py它不工作,如果我使用vim在文件中添加一些access-log ,這是行不通的既不。

為什么?

之前flush不寫\\0readline\\0它不會繼續或其他什么東西?

flushreadline的詳細信息是什么?

# log.py

f = open("access-log","w")

import time, random
while True:
    time.sleep(random.random())
    n = random.randint(0,len(ips)-1)
    m = random.randint(0,len(docs)-1)
    t = time.time()
    date = time.strftime("[%d/%b/%Y:%H:%M:%S -0600]",time.localtime(t))
    print >>f,"%s - - %s %s" % (ips[n],date,docs[m])
    f.flush()


# follow.py

import time
def follow(thefile):
    thefile.seek(0,2)      # Go to the end of the file
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)    # Sleep briefly
            continue
        yield line

# Example use
if __name__ == '__main__':
    logfile = open("access-log")
    for line in follow(logfile):
        print line,

如果先運行follow.py ,它將打開訪問日志並不斷嘗試從中讀取內容。

但是隨后log.py出現並調用open("access-log", "w") ,它刪除了現有的access-log文件並創建了一個新文件。

由於follow.py已打開原始文件,因此操作系統會維護該文件的文件句柄,但文件名不再相同(實際上根本沒有名稱) follow.py永遠都不知道新文件已創建,並且永遠無法讀取原始文件句柄。

也許log.py應該使用"a"而不是"w"來調用open?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM