python - 跟踪日志文件

标签 python linux cherrypy

我想在我的网站上添加一个日志查看器选项卡。该选项卡应该打印整个日志文件,然后仅打印新行(例如 Linux 中的 tail -F 命令)。客户端使用 HTML 和 Javascript,服务器端使用 Python。

这是我的 tail Python 函数(我在网上找到的):

@cherrypy.expose
def tail(self):
    filename = '/opt/abc/logs/myLogFile.log' 
    f = subprocess.Popen(['tail','-F',filename],\
            stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    p = select.poll()
    p.register(f.stdout)

    while True:
        if p.poll(1):
            print f.stdout.readline()
    time.sleep(1)

这段代码确实打印了整个日志文件。但是,每次我向文件添加新行时,文件都会从头开始打印,而不是打印新行。

有什么解决办法吗?我是 Python 的新手,所以我将不胜感激任何帮助。

最佳答案

查看 pytailer

https://github.com/six8/pytailer

特别是 follow 命令:

# Follow the file as it grows
for line in tailer.follow(open('/opt/abc/logs/myLogFile.log')):
    print line

关于python - 跟踪日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32375374/

相关文章:

python - 在散点图中突出显示特定点(基于条件)

python - 跟踪 python 中列表和字典的更改?

linux - CSV grep 但保留标题

python - 无法在cherrypy中包含css

python - 在 CherryPy 中,是否可以为文件夹名称添加别名?

python - 是否有用 PLY 编写的 Python(或子集)语法或词法分析器和解析器?

javascript - execute_script() 在带有 selenium phantomjs 的 python 中不起作用

java - Java JVM 是否使用 pthread?

正则表达式 sed 问题

python - python输出中的特殊字符给出错误消息