一个进程在运行,并在不断的写log,你需要实时监控log文件的更新(一般是debug时用),怎么办,不断的打开,关闭文件吗? 不用,至少有两个方法,来自两个很常用的命令:
可以很容易的模拟一下:
$ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
写一个类似于tail的程序,其实也蛮简单的:
# 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
这个可以做为一个不错的面试题。
原文:http://www.cnblogs.com/baiyanhuang/p/3832906.html