1

我正在尝试从处理的方法返回一个值。我是使用 pyinotify 的新手,代码是:

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"

但是当我打开 file.json 时,endGame 变量永远不会变为 True。我究竟做错了什么?

4

1 回答 1

0

问题出在您的处理程序中。让我们看一下代码(我将在重要的行中添加注释):

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

因此,您在方法范围内定义新变量process_IN_OPEN。如果要引用EventHandler实例属性,则需要添加 self :

self.endGame = True
于 2012-08-20T07:56:14.243 回答