<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>利用pyinotify监控文件内容,像tailf命令但比它更强 - 秋忆 - 博客园</title> <link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=PX31qVjOE47mNaZI9JUSFK-ajuzMnpXA9PeteRNR1Qw1"/> <link id="MainCss" type="text/css" rel="stylesheet" href="/skins/Valentine/bundle-Valentine.css?v=H8ka5jC7bcVL1EYolUCmW7BdOnIzURDHAa9DoJarGxs1"/> <link type="text/css" rel="stylesheet" href="/blog/customcss/30387.css?v=8x%2btpTnxnELPx%2fxUIMt%2b94Jt6CA%3d"/> <link id="mobile-style" media="only screen and (max-width: 767px)" type="text/css" rel="stylesheet" href="/skins/Valentine/bundle-Valentine-mobile.css?v=d9LctKHRIQp9rreugMcQ1-UJuq_j1fo0GZXTXj8Bqrk1"/> <link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/qiuyi21/rss"/> <link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/qiuyi21/rsd.xml"/> <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/qiuyi21/wlwmanifest.xml"/> <script src="//common.cnblogs.com/scripts/jquery-2.2.0.min.js"></script> <script type="text/javascript">var currentBlogApp = 'qiuyi21', cb_enable_mathjax=false;var isLogined=false;</script> <script src="/bundles/blog-common.js?v=oFpq70v3U1-c9rdP99iicoTFTCbQZF5NZNtH0AloVxg1" type="text/javascript"></script> </head> <body> <a name="top"></a> <!--done--> <TABLE cellpadding="0" cellspacing="0" border="0" align="center" width="100%"> <TR> <TD width=184 background="/skins/Valentine/images/banner1.gif"></TD> <TD background="/skins/Valentine/images/banner.gif"> <!--done--> <div class="header"> <div class="headerText"> <a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/qiuyi21/">秋忆博客</a><br> <span style="font-size:12px;color:#4371A6;padding-left:20;">若是有缘,时间空间都不是距离,若是无缘,终日相聚也无法会意,凡事不必太在意,更不需去强求。</span> </div> </div> </TD> <TD width=295 background="/skins/Valentine/images/banner2.gif"></TD> </TR> </TABLE> <div id="mylinks"> <!--done--> <a id="blog_nav_sitehome" class="menu" href="http://www.cnblogs.com/">博客园</a> <a id="blog_nav_myhome" class="mainmenu" href="http://www.cnblogs.com/qiuyi21/">首页</a> <a id="blog_nav_newpost" class="mainmenu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a> <a id="MyLinks1_NewArticleLink" class="mainmenu" href="/EnterMyBlog.aspx?NewArticle=1">新文章</a> <a id="blog_nav_contact" accesskey="9" class="mainmenu" rel="nofollow" href="https://msg.cnblogs.com/send/%E7%A7%8B%E5%BF%86">联系</a> <a id="blog_nav_rss" class="mainmenu" href="http://www.cnblogs.com/qiuyi21/rss">订阅</a><a id="blog_nav_rss_image" href="http://www.cnblogs.com/qiuyi21/rss"><img src="//www.cnblogs.com/images/xml.gif" alt="订阅" /></a> <a id="blog_nav_admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">管理</a> </div> <div id="mytopmenu"> <DIV id="mystats"> <div id="blog_stats"> <!--done--> <div class="blogStats"> posts - 55,comments - 181,trackbacks - 2 </div></div></DIV> </div> <div id="leftcontent"> <DIV id="leftcontentcontainer"> <div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script><br> <!--done--> <div class="newsItem"> <div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script> </div> <div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script></DIV> </div> <div id="centercontent"> <div id="post_detail"> <!--done--> <div class = "post"> <div class = "postTitle"> <a id="cb_post_title_url" class="postTitle2" href="https://www.cnblogs.com/qiuyi21/p/7439793.html">利用pyinotify监控文件内容,像tailf命令但比它更强</a> </div> <div id="cnblogs_post_body" class="blogpost-body"><p>Linux的tail/tailf命令使用了内核提供的inotify功能,下面的Python例子也使用inotify实现比tail/tailf更强的监控文件功能。</p> <p> </p> <p>watchfile.py</p> <div class="cnblogs_Highlighter"> <pre class="brush:python;gutter:false;">#!/usr/bin/python import sys, os, pyinotify notifier = None monfile = None lastsize = 0 wm = None wd = 0 def roll_file(filename): global lastsize fd = os.open(filename, os.O_RDONLY) try: newsize = os.fstat(fd).st_size if newsize <= lastsize: return os.lseek(fd, lastsize, os.SEEK_SET) while True: data = os.read(fd, 4096) if not data: break sys.stdout.write(data) sys.stdout.flush() pos = os.lseek(fd, 0, os.SEEK_CUR) lastsize = pos if pos != lastsize else newsize finally: os.close(fd) class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): if monfile == event.pathname: global wd wd = wm.add_watch(monfile, pyinotify.IN_MODIFY).values()[0] roll_file(monfile) def process_IN_DELETE(self, event): global wd, lastsize if monfile == event.pathname: if wd > 0: try: wm.rm_watch(wd, quiet=False) except pyinotify.WatchManagerError: pass wd = 0 lastsize = 0 def process_IN_MOVED_FROM(self, event): self.process_IN_DELETE(event) def process_IN_MOVED_TO(self, event): self.process_IN_DELETE(event) self.process_IN_CREATE(event) def process_IN_MODIFY(self, event): roll_file(monfile) def main(): global notifier, lastsize, wm, wd, monfile monfile = os.path.abspath(sys.argv[1]) print "path={0}".format(monfile) lastsize = os.stat(monfile).st_size wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, EventHandler()) wd = wm.add_watch(monfile, pyinotify.IN_MODIFY).values()[0] wm.add_watch(os.path.dirname(monfile), pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO) print "watching {0} ...".format(monfile) while True: notifier.process_events() if notifier.check_events(): notifier.read_events() if __name__ == "__main__": try: main() finally: if notifier: notifier.stop() </pre> </div> <p> </p> <p>使用方法:</p> <p>./watchfile.py ~/test.log</p> <p> </p> <p>被监控的文件做改名、删除、创建的操作都可以继续监控。</p></div><div id="MySignature"></div> <div class="clear"></div> <div id="blog_post_info_block"> <div id="BlogPostCategory"></div> <div id="EntryTag"></div> <div id="blog_post_info"> </div> <div class="clear"></div> <div id="post_next_prev"></div> </div> <div class = "postDesc">posted on <span id="post-date">2017-08-27 10:49</span> <a href='http://www.cnblogs.com/qiuyi21/'>秋忆</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>) <a href ="https://i.cnblogs.com/EditPosts.aspx?postid=7439793" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(7439793);return false;">收藏</a></div> </div> <script type="text/javascript">var allowComments=true,cb_blogId=30387,cb_entryId=7439793,cb_blogApp=currentBlogApp,cb_blogUserGuid='bc823d0b-63cf-dd11-9e4d-001cf0cd104b',cb_entryCreatedDate='2017/8/27 10:49:00';loadViewCount(cb_entryId);var cb_postType=1;</script> </div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script> <div id='comment_form' class='commentform'> <a name='commentform'></a> <div id='divCommentShow'></div> <div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>刷新评论</a><a href='#' onclick='return RefreshPage();'>刷新页面</a><a href='#top'>返回顶部</a></div> <div id='comment_form_container'></div> <div class='ad_text_commentbox' id='ad_text_under_commentbox'></div> <div id='ad_t2'></div> <div id='opt_under_post'></div> <div id='cnblogs_c1' class='c_ad_block'></div> <div id='under_post_news'></div> <div id='cnblogs_c2' class='c_ad_block'></div> <div id='under_post_kb'></div> <div id='HistoryToday' class='c_ad_block'></div> <script type='text/javascript'> fixPostBody(); setTimeout(function () { incrementViewCount(cb_entryId); }, 50); deliverAdT2(); deliverAdC1(); deliverAdC2(); loadNewsAndKb(); loadBlogSignature(); LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid); GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate, cb_postType); loadOptUnderPost(); GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate); </script> </div> </div> <!--done--> <div class="footer"> Copyright ©2018 秋忆 Powered By<a href="/">博客园</a> 模板提供:<a href="http://blog.hjenglish.com">沪江博客</a> </div> <!--PageEndHtml Block Begin--> <span style="display:none"><script src="https://s76.cnzz.com/stat.php?id=292658&web_id=292658" language="javascript" charset="gb2312"></script></span> <!--PageEndHtml Block End--> </body> </html>
利用pyinotify监控文件
最新推荐文章于 2023-04-03 19:25:21 发布