Search code examples
pythonpyinotify

pyinotify return value from handled event


I'm trying to return a value from handled method. I'm very newbie using pyinotify, the code is:

import pyinotify
import time


wm = pyinotify.WatchManager()
mask = pyinotify.IN_OPEN

class EventHandler(pyinotify.ProcessEvent):
    endGame = False
    def process_IN_OPEN(self, event):
        print "Opening:", event.pathname
        endGame = True

handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)

wdd = wm.add_watch('./file.json', mask, rec=True)
wm.rm_watch(wdd.values())

while not handler.endGame:
    time.sleep(1)

notifier.stop()
print "end game"

But when I open file.json, the endGame variable never turns to True. What am I doing wrong?


Solution

  • The problem is in your handler. Let's look at the code (I'll add comments to significant lines):

    class EventHandler(pyinotify.ProcessEvent):
        endGame = False   # Here class attribute "endGame" is declared
    
        def process_IN_OPEN(self, event):
            print "Opening:", event.pathname
            endGame = True  # Here !local variable! is defined process_IN_OPEN
    

    So, you define new variable in the scope of process_IN_OPEN method. You need to add self if you want to refer to EventHandler instance attribute:

    self.endGame = True