def start(self):
for f in os.listdir(self.path):
name = file2mod(f)
if not name:
continue
self._load(name)
wm = pyinotify.WatchManager()
wm.add_watch(self.path,
pyinotify.IN_DELETE |
pyinotify.IN_CREATE |
pyinotify.IN_MODIFY ,
rec = False)
handle = EventHandler(self)
self._notifier = pyinotify.TornadoAsyncNotifier(
wm, self._ioloop, default_proc_fun = handle)
python类WatchManager()的实例源码
def __init__(self, rt):
ManagerPlugin.__init__(self, rt)
self.git_repo = GitRepo(directory=self.rt.paths.skills,
url='https://github.com/MatthewScholefield/mycroft-light.git',
branch='skills',
update_freq=1)
self.blacklist = self.config['blacklist']
sys.path.append(self.rt.paths.skills)
GroupPlugin.__init__(self, SkillPlugin, 'mycroft.skills', '_skill')
for cls in self._classes.values():
cls.rt = rt
self.init_plugins()
# The watch manager stores the watches and provides operations on watches
wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MOVED_TO
skills_dir = self.rt.paths.skills
handler = EventHandler(self)
notifier = pyinotify.ThreadedNotifier(wm, handler)
notifier.daemon = True
wdd = wm.add_watch(skills_dir, mask, rec=True)
notifier.start()
def file_monitor(path='.', client=None):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE | IN_MODIFY
notifier = AsyncNotifier(wm, EventHandler(client))
wm.add_watch(path, mask, auto_add=True, rec=True)
if not os.path.isfile(path):
logger.debug("File %s does not exist." % path)
sys.exit(3)
else:
logger.debug("Now starting monitor file %s." % path)
global f
f = open(path, 'r')
st_size = os.stat(path)[6]
f.seek(st_size)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
print "keyboard Interrupt."
notifier.stop()
break
def __init__(self, listen_host, listen_port, server_key, server_cert, ca_cert, image_path, image_types, exec_handlers, static_paths):
websockets = WebSockets()
wm = pyinotify.WatchManager()
inotify_handler = INotifyHandler(websockets)
self._notifier = pyinotify.Notifier(wm, inotify_handler)
for image_type in image_types:
type_path = os.path.join(image_path, image_type)
wm.add_watch(type_path, pyinotify.IN_MOVED_TO)
exec_handlers = dict(x.split('=', 1) for x in (exec_handlers or []))
static_paths = dict(x.split('=', 1) for x in (static_paths or []))
http_handler = HTTPRequestHandler(image_path, image_types, exec_handlers, static_paths, websockets)
self._httpd = geventserver.WSGIServer(
(listen_host, listen_port),
http_handler,
keyfile=server_key,
certfile=server_cert,
ca_certs=ca_cert,
cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_TLSv1_2)
def file_monitor(path='.', client=None):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE | IN_MODIFY
notifier = AsyncNotifier(wm, EventHandler(client))
wm.add_watch(path, mask, auto_add=True, rec=True)
if not os.path.isfile(path):
logger.debug("File %s does not exist." % path)
sys.exit(3)
else:
logger.debug("Now starting monitor file %s." % path)
global f
f = open(path, 'r')
st_size = os.stat(path)[6]
f.seek(st_size)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
print "keyboard Interrupt."
notifier.stop()
break
def file_monitor(path='.', client=None):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE | IN_MODIFY
notifier = AsyncNotifier(wm, EventHandler(client))
wm.add_watch(path, mask, auto_add=True, rec=True)
if not os.path.isfile(path):
logger.debug("File %s does not exist." % path)
sys.exit(3)
else:
logger.debug("Now starting monitor file %s." % path)
global f
f = open(path, 'r')
st_size = os.stat(path)[6]
f.seek(st_size)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
print "keyboard Interrupt."
notifier.stop()
break
def setup_inotify(configuration):
class EventHandler(pyinotify.ProcessEvent):
def process_default(self, event):
basename = os.path.basename(event.pathname)
if basename == 'node.json':
log("node.json changed")
configuration.parse_node_json()
elif basename == 'config.json':
log("config.json changed!")
configuration.parse_config_json()
elif basename.endswith('.py'):
abort_service("python file changed")
wm = pyinotify.WatchManager()
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.daemon = True
notifier.start()
wm.add_watch('.', pyinotify.IN_MOVED_TO)
def setup_inotify(configuration):
class EventHandler(pyinotify.ProcessEvent):
def process_default(self, event):
basename = os.path.basename(event.pathname)
if basename == 'node.json':
log("node.json changed")
configuration.parse_node_json()
elif basename == 'config.json':
log("config.json changed!")
configuration.parse_config_json()
elif basename.endswith('.py'):
abort_service("python file changed")
wm = pyinotify.WatchManager()
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.daemon = True
notifier.start()
wm.add_watch('.', pyinotify.IN_MOVED_TO)
def setup_inotify(configuration):
class EventHandler(pyinotify.ProcessEvent):
def process_default(self, event):
basename = os.path.basename(event.pathname)
if basename == 'node.json':
log("node.json changed")
configuration.parse_node_json()
elif basename == 'config.json':
log("config.json changed!")
configuration.parse_config_json()
elif basename.endswith('.py'):
abort_service("python file changed")
wm = pyinotify.WatchManager()
notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.daemon = True
notifier.start()
wm.add_watch('.', pyinotify.IN_MOVED_TO)
def watch_config_changes(config_path, queues, nuimo_apps, processes, ha_api_url, ble_adapter_name):
class ModificationHandler(pyinotify.ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
if hasattr(event, 'pathname') and event.pathname == config_path:
logger.info("Config file was changed, reloading it...")
update_from_config_file(config_path, queues, nuimo_apps, processes, ha_api_url, ble_adapter_name)
handler = ModificationHandler()
watch_manager = pyinotify.WatchManager()
notifier = pyinotify.Notifier(watch_manager, handler)
# IN_CLOSE_WRITE is fired when the file was closed after modification
# in opposite to IN_MODIFY which is called for each partial write
watch_manager.add_watch(config_path, pyinotify.IN_CLOSE_WRITE)
logger.info("Listening to changes of: %s", config_path)
notifier.loop()
logger.info("Stopped listening to changes of: %s", config_path)
def file_monitor(path='.', client=None):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE | IN_MODIFY
notifier = AsyncNotifier(wm, EventHandler(client))
wm.add_watch(path, mask, auto_add=True, rec=True)
if not os.path.isfile(path):
logger.debug("File %s does not exist." % path)
sys.exit(3)
else:
logger.debug("Now starting monitor file %s." % path)
global f
f = open(path, 'r')
st_size = os.stat(path)[6]
f.seek(st_size)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
print "keyboard Interrupt."
notifier.stop()
break
def __init__(self, **kwargs):
super(Utility, self).__init__(**kwargs)
self.rsync = Rsync(**kwargs)
self.syncevt = SyncEvent(sync_method = self.rsync.sync)
self.watchman = None #pyinotify.WatchManager()
self.watch_delay = kwargs.get("delay", 30)
self.notifier = None
self.statusq = list()
default_events = [
"IN_CLOSE_WRITE",
"IN_CREATE",
"IN_DELETE",
"IN_MOVED_FROM",
"IN_MOVED_TO"
]
self.events = kwargs.get("watch_events", default_events)
def start_rtsync(self):
if self.notifier is None:
self.watchman = pyinotify.WatchManager()
self.notifier = pyinotify.ThreadedNotifier(self.watchman, self.syncevt, read_freq=self.watch_delay)
self.notifier.coalesce_events(True)
mask = self.get_mask()
wpaths = self.syncevt.get_wpaths()
for awpath in wpaths:
self.logger.debug("adding %s to sync watches" %awpath['src'])
wpath = copy.deepcopy(awpath)
self.watchman.add_watch(wpath['src'], mask, rec=True, auto_add=True)
# do an initial sync, dont wait for rsync to finish.
wpath['wait']=False
self.rsync.sync(**wpath)
self.logger.debug("starting notifier...")
self.notifier.start()
else:
self.logger.debug("start_rtsync called by notifier not none.")
def run(self):
self.running = True
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm)
def inotify_callback(event):
if event.mask == pyinotify.IN_CLOSE_WRITE:
self.populate_app(event.pathname)
elif event.mask == pyinotify.IN_DELETE:
with self.lock:
for cmd, data in self.apps.items():
if data[2] == event.pathname:
del self.apps[cmd]
break
for p in DESKTOP_PATHS:
if os.path.exists(p):
wm.add_watch(p,
pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE,
inotify_callback)
notifier.loop()
def watch(self):
# watch changes to the config file -- needs to be run in a separate thread
configStatusManager = pyinotify.WatchManager()
configStatusNotifier = pyinotify.Notifier(configStatusManager)
configStatusManager.add_watch(self.path, pyinotify.IN_CLOSE_WRITE, proc_fun=PipelinesConfigUpdateHandler(config=self))
configStatusNotifier.loop()
def watch(self):
# watch changes to the config file -- needs to be run in a separate thread
configStatusManager = pyinotify.WatchManager()
configStatusNotifier = pyinotify.Notifier(configStatusManager)
configStatusManager.add_watch(self.path, pyinotify.IN_CLOSE_WRITE, proc_fun=PipelineConfigUpdateHandler(config=self))
configStatusNotifier.loop()
def check_support():
global w_pyinotify, w_fam, w_gamin
try:
import pyinotify as w_pyinotify
except ImportError:
w_pyinotify = None
else:
try:
wm = w_pyinotify.WatchManager()
wm = w_pyinotify.Notifier(wm)
wm = None
except:
raise
w_pyinotify = None
try:
import gamin as w_gamin
except ImportError:
w_gamin = None
else:
try:
test = w_gamin.WatchMonitor()
test.disconnect()
test = None
except:
w_gamin = None
try:
import _fam as w_fam
except ImportError:
w_fam = None
else:
try:
test = w_fam.open()
test.close()
test = None
except:
w_fam = None
def wait_pyinotify(self, bld):
class PE(w_pyinotify.ProcessEvent):
def stop(self, event):
self.notif.ev = True
self.notif.stop()
raise ValueError("stop for delete")
process_IN_DELETE = stop
process_IN_CLOSE = stop
process_default = stop
proc = PE()
wm = w_pyinotify.WatchManager()
notif = w_pyinotify.Notifier(wm, proc)
proc.notif = notif
# well, we should add all the folders to watch here
for x in self.enumerate(bld.srcnode):
wm.add_watch(x, w_pyinotify.IN_DELETE | w_pyinotify.IN_CLOSE_WRITE)
try:
# pyinotify uses an infinite loop ... not too nice, so we have to use an exception
notif.loop()
except ValueError:
pass
if not hasattr(notif, 'ev'):
raise KeyboardInterrupt
def check_support():
global w_pyinotify, w_fam, w_gamin
try:
import pyinotify as w_pyinotify
except ImportError:
w_pyinotify = None
else:
try:
wm = w_pyinotify.WatchManager()
wm = w_pyinotify.Notifier(wm)
wm = None
except:
raise
w_pyinotify = None
try:
import gamin as w_gamin
except ImportError:
w_gamin = None
else:
try:
test = w_gamin.WatchMonitor()
test.disconnect()
test = None
except:
w_gamin = None
try:
import _fam as w_fam
except ImportError:
w_fam = None
else:
try:
test = w_fam.open()
test.close()
test = None
except:
w_fam = None
def wait_pyinotify(self, bld):
class PE(w_pyinotify.ProcessEvent):
def stop(self, event):
self.notif.ev = True
self.notif.stop()
raise ValueError("stop for delete")
process_IN_DELETE = stop
process_IN_CLOSE = stop
process_default = stop
proc = PE()
wm = w_pyinotify.WatchManager()
notif = w_pyinotify.Notifier(wm, proc)
proc.notif = notif
# well, we should add all the folders to watch here
for x in self.enumerate(bld.srcnode):
wm.add_watch(x, w_pyinotify.IN_DELETE | w_pyinotify.IN_CLOSE_WRITE)
try:
# pyinotify uses an infinite loop ... not too nice, so we have to use an exception
notif.loop()
except ValueError:
pass
if not hasattr(notif, 'ev'):
raise KeyboardInterrupt
def check_support():
global w_pyinotify, w_fam, w_gamin
try:
import pyinotify as w_pyinotify
except ImportError:
w_pyinotify = None
else:
try:
wm = w_pyinotify.WatchManager()
wm = w_pyinotify.Notifier(wm)
wm = None
except:
raise
w_pyinotify = None
try:
import gamin as w_gamin
except ImportError:
w_gamin = None
else:
try:
test = w_gamin.WatchMonitor()
test.disconnect()
test = None
except:
w_gamin = None
try:
import _fam as w_fam
except ImportError:
w_fam = None
else:
try:
test = w_fam.open()
test.close()
test = None
except:
w_fam = None
def _get_notifier():
'''
Check the context for the notifier and construct it if not present
'''
if 'pulsar.notifier' not in __context__:
__context__['pulsar.queue'] = collections.deque()
wm = pyinotify.WatchManager()
__context__['pulsar.notifier'] = pyinotify.Notifier(wm, _enqueue)
return __context__['pulsar.notifier']
def enable_inotify(self):
self._wm = pyinotify.WatchManager()
self._notifier = pyinotify.Notifier(self._wm, lambda *a, **b: False)
self._wm.add_watch('/dev/input', pyinotify.IN_CREATE, False)
self.daemon.get_poller().register(self._notifier._fd,
self.daemon.get_poller().POLLIN, self._inotify_cb)
def main():
wm = pyinotify.WatchManager()
# watched events
mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE
notifier = pyinotify.AsyncNotifier(wm, EventHandler())
wdd = wm.add_watch(SAMPLES_DIR, mask, rec=True)
asyncore.loop()
def start_config_watch(self):
wm = pyinotify.WatchManager()
wm.add_watch('./config/mitmf.conf', pyinotify.IN_MODIFY)
notifier = pyinotify.Notifier(wm, self)
t = threading.Thread(name='ConfigWatcher', target=notifier.loop)
t.setDaemon(True)
t.start()
def _get_notifier():
'''
Check the context for the notifier and construct it if not present
'''
if 'pulsar.notifier' not in __context__:
__context__['pulsar.queue'] = collections.deque()
wm = pyinotify.WatchManager()
__context__['pulsar.notifier'] = pyinotify.Notifier(wm, _enqueue)
return __context__['pulsar.notifier']
def __init__(self, monitor_path, bcloud_app):
super(WatchFileChange, self).__init__()
self.setDaemon(True)
self.monitor_path = monitor_path
self.bcloud_app = bcloud_app
self.submitter = TaskSubmitter(self.bcloud_app)
self.submitter.start()
self.handler = EventHandler(self.monitor_path, self.bcloud_app,
self.submitter)
self.wm = pyinotify.WatchManager()
self.wdds = self.wm.add_watch(self.monitor_path, MASK, rec=True,
auto_add=True)
self.notifyer = pyinotify.Notifier(self.wm, self.handler)
def start_config_watch(self):
wm = pyinotify.WatchManager()
wm.add_watch('./config/mitmf.conf', pyinotify.IN_MODIFY)
notifier = pyinotify.Notifier(wm, self)
t = threading.Thread(name='ConfigWatcher', target=notifier.loop)
t.setDaemon(True)
t.start()
def run(self):
if running_on_linux()==True:
print("thread: start")
wm = pyinotify.WatchManager()
print("wathcing path",self.watch_path)
ret=wm.add_watch(self.watch_path, pyinotify.IN_CLOSE_WRITE, self.onChange,False,False)
print(ret)
print("thread: start notifyer",self.notifier)
self.notifier = pyinotify.Notifier(wm)
try:
while 1:
self.notifier.process_events()
if self.notifier.check_events():
self.notifier.read_events()
#self.notifier.loop()
except:
print("error in notify",sys.exc_info()[0])
else:
hDir = win32file.CreateFile (self.watch_path,FILE_LIST_DIRECTORY,win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,None,win32con.OPEN_EXISTING,win32con.FILE_FLAG_BACKUP_SEMANTICS,None)
while 1:
results = win32file.ReadDirectoryChangesW (hDir,1024,True,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None)
for action, file in results:
full_filename = os.path.join (self.watch_path, file)
self.onChange(full_filename)
def _get_notifier():
'''
Check the context for the notifier and construct it if not present
'''
if 'pulsar.notifier' not in __context__:
__context__['pulsar.queue'] = collections.deque()
wm = pyinotify.WatchManager()
__context__['pulsar.notifier'] = pyinotify.Notifier(wm, _enqueue)
return __context__['pulsar.notifier']