A process is running and constantly writing logs. You need to monitor log file updates in real time (usually used in debug). What should you do? Keep opening and closing files? No. There are at least two methods from two frequently-used commands:
- Tail-F log.txt, another process is writing logs, and you can use tail to print new content in real time.
- Less log.txt. If you want to monitor updates, press F. If you want to suspend monitoring, press Ctrl + C to view the updates on pages up and down. If you want to continue monitoring, press F. This function is more powerful than tail.
It is easy to simulate:
- Continuously update files in a shell:
$ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
- In another shell, tail-F log.txt or less log.txt
Writing a program similar to tail is actually quite simple:
# 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 EOFimport sysimport timefilename = sys.argv[1]with open(filename, ‘r‘, 0) as fh: while True: line = fh.readline() if not line: time.sleep(1) else: print line
This can be used as a good interview question.