python web界面整合 tail_python实现tail(考虑到几种特殊情况)

#!-*- coding: utf-8 -*-

#################################################################################

#Copyright (c) 2015 XX.com, Inc. All Rights Reserved#

################################################################################

#################################################################################This module provide ...#Third libs those depend on:################################################################################

"""Compiler Python 2.7.10

Authors: XX(XX@baidu.com)

Date: 2015-09-09 12:57:41

Todo: nothing $XX$2015-09-09"""

"""SYS LIBS"""

importosimportreimportsysimporttimeimporttraceback"""THIRD LIBS"""

try:#import the third libs there.

pass

exceptImportError as e:printe

os._exit(-1)"""CUSTOM libs

Strongly recommend using abs path when using custmo libs."""

#Good behaviors.#It means refusing called like from xxx import *#When `__all__` is []

__all__ =[]

reload(sys)

sys.setdefaultencoding('utf-8')defsend_error(msg):"""Send error to email."""

printmsg#********************************************************#* Global defines start. *#********************************************************

#********************************************************#* Global defines end. *#********************************************************

classTail(object):"""Python-Tail - Unix tail follow implementation in Python.

python-tail can be used to monitor changes to a file.

Example:

import tail

# Create a tail instance

t = tail.Tail('file-to-be-followed')

# Register a callback function to be called when a new line is found in the followed file.

# If no callback function is registerd, new lines would be printed to standard out.

t.register_callback(callback_function)

# Follow the file with 5 seconds as sleep time between iterations.

# If sleep time is not provided 1 second is used as the default time.

t.follow(s=5)"""

'''Represents a tail command.'''

def __init__(self, tailed_file):'''Initiate a Tail instance.

Check for file validity, assigns callback function to standard out.

Arguments:

tailed_file - File to be followed.'''self.check_file_validity(tailed_file)

self.tailed_file=tailed_file

self.callback=sys.stdout.write

self.try_count=0try:

self.file_= open(self.tailed_file, "r")

self.size=os.path.getsize(self.tailed_file)#Go to the end of file

self.file_.seek(0, 2)except:raise

defreload_tailed_file(self):"""Reload tailed file when it be empty be `echo "" > tailed file`, or

segmentated by logrotate."""

try:

self.file_= open(self.tailed_file, "r")

self.size=os.path.getsize(self.tailed_file)#Go to the head of file

self.file_.seek(0, 1)returnTrueexcept:returnFalsedef follow(self, s=0.01):"""Do a tail follow. If a callback function is registered it is called with every new line.

Else printed to standard out.

Arguments:

s - Number of seconds to wait between each iteration; Defaults to 1."""

whileTrue:

_size=os.path.getsize(self.tailed_file)if _size

self.try_count+= 1

else:

self.try_count=0

self.size=os.path.getsize(self.tailed_file)breaktime.sleep(0.1)if self.try_count == 10:raise Exception("Open %s failed after try 10 times" %self.tailed_file)else:

self.size=_size

curr_position=self.file_.tell()

line=self.file_.readline()if notline:

self.file_.seek(curr_position)

elif not line.endswith("\n"):

self.file_.seed(curr_position)else:

self.callback(line)

time.sleep(s)defregister_callback(self, func):"""Overrides default callback function to provided function."""self.callback=funcdefcheck_file_validity(self, file_):"""Check whether the a given file exists, readable and is a file"""

if notos.access(file_, os.F_OK):raise TailError("File '%s' does not exist" %(file_))if notos.access(file_, os.R_OK):raise TailError("File '%s' not readable" %(file_))ifos.path.isdir(file_):raise TailError("File '%s' is a directory" %(file_))classTailError(Exception):"""Custom error type."""

def __init__(self, msg):"""Init."""self.message=msgdef __str__(self):"""str."""

returnself.messageif __name__ == '__main__':

t= Tail("/home/syslog/switch.log")defprint_msg(msg):printmsg

t.register_callback(print_msg)

t.follow()"""vim: set ts=4 sw=4 sts=4 tw=100 et:"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Python Tornado 上实现 "tail" 功能,可以使用 Tornado 的异步 IO 特性和 Python 的标准库 `subprocess`。 以下是一个简单的示例代码: ```python import tornado.web import tornado.websocket import subprocess class TailHandler(tornado.websocket.WebSocketHandler): def open(self): self.process = subprocess.Popen(['tail', '-f', '/path/to/log/file'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stream = tornado.ioloop.IOLoop.current().add_handler(self.process.stdout.fileno(), self.on_read, tornado.ioloop.IOLoop.READ) def on_message(self, message): # 不需要处理客户端发送的消息 pass def on_close(self): tornado.ioloop.IOLoop.current().remove_handler(self.process.stdout.fileno()) def on_read(self, fd, events): if events & tornado.ioloop.IOLoop.READ: # 从 stdout 读取数据并发送给客户端 data = self.process.stdout.readline() if data: self.write_message(data.decode('utf-8')) else: self.close() ``` 上述代码实现了一个 WebSocket 处理器 `TailHandler`,用于向客户端实时发送日志文件的内容。在 `open()` 方法中启动一个 `tail -f` 进程,并将其 stdout 指向 `self.process.stdout`。然后,使用 Tornado 的 `add_handler()` 方法将 `self.process.stdout` 的文件描述符注册到 IOLoop 上,以便在数据可读时触发 `on_read()` 方法。 `on_read()` 方法中从 `self.process.stdout` 读取数据并将其发送给客户端。如果读取到的数据为空,则关闭 WebSocket 连接。 可以将 `TailHandler` 添加到 Tornado 的应用程序中,并在相应的路由上进行映射。例如: ```python app = tornado.web.Application([ (r'/tail', TailHandler), ]) ``` 这样,当客户端通过 WebSocket 连接到 `/tail` 路由时,将实时接收到指定日志文件的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值