zoukankan      html  css  js  c++  java
  • Pytho实现tail -f

    实现Python版的tail -f功能

    tail -f 的功能非常好用。我们用Python也可以实现这样的功能。
    实现的原理是通过Python版本的inotify获得文件的更新消息,从而读取更新的行。pyinotify的下载地址https://github.com/seb-m/pyinotify
    下载解压后得到如下文件
    #ls
    ACKS  build  common  COPYING  dist  MANIFEST.in  old  python2  python3  README.md  setup.py
    执行如下命令进行安装。
    python setup.py build
    python setup.py install
    然后就可以使用Python版本的inotify功能了。
    下面是我写的一个简单的tail -f文件的实现。
    #!/usr/bin/python
    
    import pyinotify
    import time
    import os
    class ProcessTransientFile(pyinotify.ProcessEvent):
        def process_IN_MODIFY(self, event):
            line = file.readline()
            if line:
                print line, # already has newline
    
    filename = '/tmp/test1234'
    file = open(filename,'r')
    #Find the size of the file and move to the end
    st_results = os.stat(filename)
    st_size = st_results[6]
    file.seek(st_size)
    
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm)
    wm.watch_transient_file(filename, pyinotify.IN_MODIFY, ProcessTransientFile)
    notifier.loop()

    tail的文件为/tmp/test1234,通过向/tmp/test1234写入内容,可以看到python脚本可以动态显示更新的内容。
    这个小脚本只是抛砖引玉。通过监听文件,尤其是日志文件可以实现很多诸如报警、自动控制等功能。
     
    本文转自 “http://www.opstool.com/article/226”
  • 相关阅读:
    [loj3364]植物比较
    [loj3366]嘉年华奖券
    [atARC105F]Lights Out on Connected Graph
    [atARC105D]Let's Play Nim
    [atARC058F]Lroha Loves Strings
    [loj3347]有趣的旅途
    [atAGC001F]Wide Swap
    [cf1392I]Kevin and Grid
    [loj3340]命运
    [loj3046]语言
  • 原文地址:https://www.cnblogs.com/cmsd/p/4070901.html
Copyright © 2011-2022 走看看