繁体   English   中英

使用pyinotify来“实时”刷新显示的文件

[英]Using pyinotify to 'live' refresh displayed file

G'day,

我有一个Raspberry Pi,它将用于在连接HDMI的显示器上显示事务日志CSV文件。 我希望显示器可以作为实时“记分板”运行,以便用户可以看到的只是日志CSV文件(如机场/航班公告板)。

有人告诉我pyinotify可以监视日志CSV文件,然后刷新该文件,而不必关闭并重新打开它? 我通读了文档,并在网上搜索了此功能,但到目前为止我还是空着。 我没有任何示例代码来演示我尝试过的操作(但!),因为我想首先确定pyinotify是否可以实现此功能,或者我是否应该查看其他内容。

我正在使用Python 3.3。

这里的任何指导将是惊人的!

谢谢!

好的,我不知道这是否有帮助,但是在这里您可以如何做到:

假设我们有一个文件:

echo "line 1" >> testfile.txt 

比编写脚本(确保您指向此文件):

import os, pyinotify

PATH = os.path.join(os.path.expanduser('~/'), 'testfile.txt')

class EventHandler(pyinotify.ProcessEvent):
    def __init__(self, *args, **kwargs):
        super(EventHandler, self).__init__(*args, **kwargs)
        self.file = open(PATH)
        self.position = 0
        self.print_lines()

    def process_IN_MODIFY(self, event):
        self.print_lines()

    def print_lines(self):
        new_lines = self.file.read()
        last_n = new_lines.rfind('\n')
        if last_n >= 0:
            self.position += last_n + 1
            print new_lines[:last_n]
        else:
            print 'no line'
        self.file.seek(self.position)

wm = pyinotify.WatchManager()
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wm.add_watch(PATH, pyinotify.IN_MODIFY, rec=True)
notifier.loop()

运行文件:

python notify.py

你会看见

line 1

而不是从另一终端向文件添加另一行(确保脚本仍在运行)

echo "line 2" >> testfile.txt

您将在脚本输出中看到它

此代码的PS积分归Nicolas Cartot所有

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM