the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


python代码实现linux下的tail功能

作者:the5fire | 标签:     | 发布:2012-07-03 11:40 p.m. | 阅读量: 15248, 14718
今天在服务器上调试程序,发现win03的服务器在查看apache输出日志的时候灰常麻烦,想到linux下系统的命令 tail就可以实时查看输出日志,于是找了下,还真有人写了个win下的tail:http://www.kuaipan.cn/file/id_12834302878348914.htm

后来想了想,自己用python写一个也不麻烦,权当练手于是有了下面的代码:


#coding=utf-8
'''
author:the5fire
blog:http://www.the5fire.com
date:2012-07-03
'''
import sys
already_print_num = 0

def get_last_line(filepath):
'''
获取未输入的行
'''
global already_print_num
import os
if not os.path.exists(filepath):
print 'no such file %s' % filepath
sys.exit()
return
readfile = open(filepath, 'r')
lines = readfile.readlines()
if len(lines) > 20 and already_print_num == 0:
#last_num = 20 #首次输出最多输出20行
#经nonoob指正,修改如下
already_print_num = len(lines) - 20

if already_print_num < len(lines):
print_lines = lines[already_print_num - len(lines):]
for line in print_lines:
print len(lines), already_print_num, line.replace('\n','')
already_print_num = len(lines)
readfile.close()



def timer(filename):
'''
每隔1秒执行一次
'''
while True:
get_last_line(filename)
import time
time.sleep(1)

if __name__ == '__main__':
if len(sys.argv) < 2:
print 'illegal params'
else:
filename = sys.argv[1]
timer(filename)

代码不是很严谨,有兴趣的自己扩展
运行方法:
把该py文件放到你要统计的日志文件所在目录,然后运行:python xxx.py logs.log(×nux系统注意权限)

为了方便测试,自己写了一个不断写文件的代码,主要是每隔10秒,写入一条数据

#coding=utf-8
'''
author:the5fire
blog:http://www.the5fire.com
date:2012-07-03
'''

import time

def writefile(filename):
counter = 0
while True:
writefile = open(filename, 'a')
writefile.write('test' + str(counter) + '\n')
writefile.close()
counter += 1
print counter
time.sleep(10)

if __name__ == '__main__':
import sys
if len(sys.argv) == 2:
filename = sys.argv[1]
writefile(filename)

使用方法同上。 - from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈

【上一篇】 vim安装和卸载插件
【下一篇】 python线程池

其他分类: