Created
October 17, 2014 02:10
-
-
Save iziang/0da4085cd91ec3bdc762 to your computer and use it in GitHub Desktop.
python模拟tail -f监控文件的变动
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 方法1 | |
with open('/tmp/track-this') as f: | |
while True: | |
line = f.readline() | |
if line: | |
print line | |
# 方法2 | |
import time | |
def follow(thefile): | |
thefile.seek(0,2) | |
while True: | |
line = thefile.readline() | |
if not line: | |
time.sleep(0.1) | |
continue | |
yield line | |
if __name__ == '__main__': | |
logfile = open("run/foo/access-log","r") | |
loglines = follow(logfile) | |
for line in loglines: | |
print line, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment