服务器上面的tail 很好用,想在线使用找个python版的,搜了一堆,发现很多的实际调试都有问题,没办法,自己找了个改进吧。
class Tail():
def __init__(self, file_name):
self.file_name = file_name
def follow(self,match, n=10):
callback = []
try:
with open(self.file_name) as f:
self._file = f
self._file.seek(0, 2)
self.file_length = self._file.tell()
mv = self.showLastLine(n)
while True:
line = self._file.readline()
if line:
if mv>0:
mv = mv - 1
continue
elif len(match)>0:
if line.find(match)>0:
callback.append(line)
else:
callback.append(line)
else:
break
except Exception:
print(Exception.args)
return callback
def showLastLine(self, n):
len_line = 100
read_len = len_line * n
block = 1
rest = 0
while True:
if read_len > self.file_length:
self._file.seek(0)
break
self._file.seek(self.file_length - read_len*block)
last_words = self._file.read(read_len)
rest = rest + last_words.count('\n')
if rest<n:
block = block + 1
continue
else:
self._file.seek(self.file_length - read_len*block)
break
return rest - n
#调用方法
log = Tail('/wwwlogs/www.17dingbao.com')
v = log.follow('Spider')
HTML页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log</title>
<style>
* {font-size: 12px;color:#666;}
p {width: 100%;}
textarea {height: 500px;width: 100%;color: forestgreen;padding: 8px;}
</style>
<script src="https://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<p>path:<input type="text" placeholder="查找文件" id="key">
<input type="text" placeholder="匹配字符" id="match">
<input style="width: 50px" type="text" value="500" id="lines">
<input type="button" value="查看" id="see">
<select id="fls" style="display: none">
<option>选择日志文件</option>
</select>
</p>
<p><textarea id="log"></textarea></p>
<script>
var path = "e:/";
function seach(fname) {
$.ajax({
url:'/log',
type:'post',
data:JSON.stringify({
file:fname,
max:parseInt($("#lines").val()),
match:$("#match").val()
}),
dataType:'json',
success:function (o) {
console.log(o);
ov = '';
for (m in o)
ov += o[m];
$("#log").val(ov);
}
});
}
$("#see").click(function () {
var fname = $("#key").val();
seach(fname);
});
$.ajax({
url:'/files?act=' + path,
dataType: 'json',
success:function (o) {
console.log(o)
if(o.length>0) {
$("#fls").show()
for(v in o) {
$("#fls").append('<option value="' + o[v] + '">' + o[v] + '</option>')
}
$("#fls").change(function (o) {
var pp = $(this).find(":selected").val();
seach(path + pp);
});
}
}
})
</script>
</body>
</html>
下面结合一下Flask,一个在线读大文件日志的Web就完成了。