简体   繁体   English

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

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

G'day, G'day,

I've got a Raspberry Pi, which will be used to display a transaction log CSV file on an HDMI-connected display. 我有一个Raspberry Pi,它将用于在连接HDMI的显示器上显示事务日志CSV文件。 I would like the display to operate as a live 'scoreboard', such that all the user can see is the log CSV file (like an airport/flight announcing board). 我希望显示器可以作为实时“记分板”运行,以便用户可以看到的只是日志CSV文件(如机场/航班公告板)。

I've been told that pyinotify can monitor the log CSV file, and then refresh the file, without having to close and reopen it? 有人告诉我pyinotify可以监视日志CSV文件,然后刷新该文件,而不必关闭并重新打开它? I've read through the documentation, and searched the web for this functionality, but I've so far come up empty. 我通读了文档,并在网上搜索了此功能,但到目前为止我还是空着。 I don't have any example code to demonstrate what I've tried (yet!), as I wanted to ascertain first of all whether this functionality is possible with pyinotify, or whether I should be looking at something else. 我没有任何示例代码来演示我尝试过的操作(但!),因为我想首先确定pyinotify是否可以实现此功能,或者我是否应该查看其他内容。

I'm using Python 3.3. 我正在使用Python 3.3。

Any guidance here would be amazing! 这里的任何指导将是惊人的!

Thanks! 谢谢!

Ok, I don't know if it's going to help but here how you can do it: 好的,我不知道这是否有帮助,但是在这里您可以如何做到:

let's say we have a file : 假设我们有一个文件:

echo "line 1" >> testfile.txt 

Than write a script (make sure you point to this file): 比编写脚本(确保您指向此文件):

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()

run the file: 运行文件:

python notify.py

you will see 你会看见

line 1

than add another line from different terminal to the file (make sure script is still running) 而不是从另一终端向文件添加另一行(确保脚本仍在运行)

echo "line 2" >> testfile.txt

and you will see it on the script output 您将在脚本输出中看到它

PS credit for this code goes to Nicolas Cartot 此代码的PS积分归Nicolas Cartot所有

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

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