一個進程在運行,並在不斷的寫log,你須要實時監控log文件的更新(通常是debug時用),怎麼辦,不斷的打開,關閉文件嗎? 不用,至少有兩個方法,來自兩個很經常使用的命令:面試
能夠很容易的模擬一下:shell
$ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
寫一個相似於tail的程序,其實也蠻簡單的:less
# Notices: # 1. the 3rd parameter of open() is to disable file buffering # so file updated by another process could be picked up correctly # but since your focus is newly added tail, enable buffering is ok too # 2. It is not necessary to fh.tell() to save the position, and then seek() # to resume, as if readline() failed, the pointer stay still at the EOF import sys import time filename = sys.argv[1] with open(filename, 'r', 0) as fh: while True: line = fh.readline() if not line: time.sleep(1) else: print line
這個能夠作爲一個不錯的面試題。spa