一个进程在运行,并在不断的写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