简体   繁体   中英

Using pyinotify to 'live' refresh displayed file

G'day,

I've got a Raspberry Pi, which will be used to display a transaction log CSV file on an HDMI-connected display. 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).

I've been told that pyinotify can monitor the log CSV file, and then refresh the file, without having to close and reopen it? 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.

I'm using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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