本文整理汇总了Python中pyinotify.WatchManager类的典型用法代码示例。如果您正苦于以下问题:Python WatchManager类的具体用法?Python WatchManager怎么用?Python WatchManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WatchManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: enabled
def enabled(self):
if not self.running:
wm = WatchManager()
self.event_handler = LibraryEvent(library=app.library)
FLAGS = ['IN_DELETE', 'IN_CLOSE_WRITE', # 'IN_MODIFY',
'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_CREATE']
masks = [EventsCodes.FLAG_COLLECTIONS['OP_FLAGS'][s]
for s in FLAGS]
mask = reduce(operator.or_, masks, 0)
if self.USE_THREADS:
print_d("Using threaded notifier")
self.notifier = ThreadedNotifier(wm, self.event_handler)
# Daemonize to ensure thread dies on exit
self.notifier.daemon = True
self.notifier.start()
else:
self.notifier = Notifier(wm, self.event_handler, timeout=100)
GLib.timeout_add(1000, self.unthreaded_callback)
for path in get_scan_dirs():
real_path = os.path.realpath(path)
print_d('Watching directory %s for %s (mask: %x)'
% (real_path, FLAGS, mask))
# See https://github.com/seb-m/pyinotify/wiki/
# Frequently-Asked-Questions
wm.add_watch(real_path, mask, rec=True, auto_add=True)
self.running = True
示例2: watch_files
def watch_files(paths, mask):
"""
Vigila los ficheros de path y encola en queue los eventos producidos.
"""
watcher = WatchManager()
mask = (EventsCodes.ALL_FLAGS.get('IN_MODIFY', 0))
@asyncio.coroutine
def send_event(event):
"""Encola un evento en la cola."""
yield from event_queue.put(event)
notifier = ThreadedNotifier(
watcher,
lambda e: asyncio.get_event_loop().call_soon_threadsafe(
asyncio.async, send_event(e)))
for path in paths:
watcher.add_watch(path, mask, rec=True)
while True:
notifier.process_events()
event_present = yield from asyncio.get_event_loop().run_in_executor(
None, notifier.check_events)
if event_present:
notifier.read_events()
示例3: directory
def directory(directory, patterns):
"""
This method monitors a directory given by the "*directory*" parameter.
It creates a notifier object. The notifier is registered to await
the "*CLOSE_WRITE*" event on a new file that matches the "*pattern*"
parameter. If there is no such event, it yields control on timeout,
defaulted to 1 second. It returns the created notifier.
Parameters
----------
file : str
File Name including path
patterns : list
A list of strings representing file extension
Returns
-------
None
"""
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
for pattern in patterns:
file = event.pathname
if file.endswith(pattern):
files.put(event.pathname)
break
wm = WatchManager()
mask = pyinotify.IN_CLOSE_WRITE
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler, timeout=1)
wdd = wm.add_watch(directory, mask, rec=False)
return notifier
示例4: main
def main():
vm = WatchManager()
vm.add_watch(monitor_dirs,ALL_EVENTS,rec = True)
en = MyEvent()
notifier = Notifier(vm,en)
notifier.loop()
示例5: watch_path
def watch_path(path, add_watch_opt=None, watcher_opt=None):
"""Tail all the files specify by path.
path: By default all files under the path, which should be a directory, are tailed.
Path could also be list of paths or a glob pattern.
The behavior can be modified by add_watch_opt.
See pyinotify.WatchManager.add_watch.
output: defaults to stdout.
can be diverted any callable with:
watcher_opt=dict(out=got_log_line)
where got_log_line() takes a tuple (log_path, log_line)
*_opt: Are pass-through to pyinotify.WatchManager.add_watch and tailall.Monitor.
See respective functions for detail.
"""
wm = WatchManager()
notifier = Notifier(wm, default_proc_fun=FsEvent())
#mask=ALL_EVENTS
#mask=IN_MOVED_TO|IN_CREATE|IN_MODIFY
mask=IN_MODIFY|IN_CLOSE_WRITE
kw=dict(rec=True, auto_add=False)
kw.update(add_watch_opt or {})
wm.add_watch(path, mask, **kw)
monitor=Monitor(watcher_opt=watcher_opt)
notifier.loop(callback=monitor.got_event)
示例6: fsMonitor
def fsMonitor(path="/data"):
wm = WatchManager()
mask = IN_DELETE | IN_MODIFY | IN_CREATE
notifier = Notifier(wm, EventHandler(), read_freq=10)
notifier.coalesce_events()
wm.add_watch(path, mask, rec=True, auto_add=True)
notifier.loop()
示例7: watch
def watch(pathes, extensions):
manager = WatchManager()
handler = Handler(extensions=extensions)
notifier = Notifier(manager, default_proc_fun=handler)
for path in pathes:
manager.add_watch(path, IN_MODIFY, rec=True, auto_add=True)
notifier.loop()
示例8: enabled
def enabled(self):
if not self.running:
wm = WatchManager()
self.event_handler = LibraryEvent(app.library)
# Choose event types to watch for
# FIXME: watch for IN_CREATE or for some reason folder copies
# are missed, --nickb
FLAGS = ['IN_DELETE', 'IN_CLOSE_WRITE',# 'IN_MODIFY',
'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_CREATE']
mask = reduce(lambda x, s: x | EventsCodes.ALL_FLAGS[s], FLAGS, 0)
if self.USE_THREADS:
print_d("Using threaded notifier")
self.notifier = ThreadedNotifier(wm, self.event_handler)
# Daemonize to ensure thread dies on exit
self.notifier.daemon = True
self.notifier.start()
else:
self.notifier = Notifier(wm, self.event_handler, timeout=100)
GLib.timeout_add(1000, self.unthreaded_callback)
for path in get_scan_dirs():
print_d('Watching directory %s for %s' % (path, FLAGS))
# See https://github.com/seb-m/pyinotify/wiki/
# Frequently-Asked-Questions
wm.add_watch(path, mask, rec=True, auto_add=True)
self.running = True
示例9: run
def run(self, location='.'):
transport = get_transport(location)
root = transport.local_abspath('.')
new_dirs = set('.')
relpaths = set('.')
while relpaths:
relpath = relpaths.pop()
paths = transport.list_dir(relpath)
for path in paths:
st = transport.stat(relpath + '/' + path)
if S_ISDIR(st.st_mode):
if path != '.bzr':
new_dirs.add(relpath + '/' + path)
relpaths.add(relpath + '/' + path)
# gather all dirs
wm = WatchManager()
added_flag = False
handler = ProcessClose()
handler._bzr_wm = wm
notifier = Notifier(wm, handler)
# read and process events
try:
while True:
if new_dirs:
for path in new_dirs:
wm.add_watch(root + '/' + path, dir_mask)
new_dirs = set()
notifier.process_events()
if notifier.check_events():
notifier.read_events()
finally:
notifier.stop()
示例10: add_watch
def add_watch(self, path):
if path not in self.watching_paths:
wm = WatchManager()
notifier = QNotifier(wm, self._emit_signal_on_change)
notifier.start()
wm.add_watch(path, mask, rec=True, auto_add=True)
self.watching_paths[path] = notifier
示例11: TrackState
class TrackState(State, ProcessEvent):
mask = (EventsCodes.OP_FLAGS['IN_DELETE']
| EventsCodes.OP_FLAGS['IN_CLOSE_WRITE'])
def __init__(self, *args, **kwargs):
State.__init__(self, *args, **kwargs)
self.wm = WatchManager()
self.notifier = Notifier(self.wm, self)
def process_IN_CLOSE_WRITE(self, event):
debug("IN_CLOSE_WRITE: %r" % (event,))
path = os.path.join(event.path, event.name)
if os.path.isfile(path) and self.acceptable(path):
self.upload(self.filename_to_File(path))
def process_IN_DELETE(self, event):
debug("IN_DELETE: %r" % (event,))
path = os.path.join(event.path, event.name)
if self.acceptable(path):
self.delete(self.filename_to_File(path))
def run(self):
for f in self.files:
f = os.path.abspath(f)
self.wm.add_watch(f, self.mask, rec=True, auto_add=True)
try:
while True:
self.notifier.process_events()
if self.notifier.check_events(100):
self.notifier.read_events()
sleep(0)
except KeyboardInterrupt:
self.notifier.stop()
示例12: run
def run(self):
self.pclose = PClose(self.path)
PC = self.pclose
# only watch these events
mask = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
# watch manager instance
wm = WatchManager()
notifier = Notifier(wm, PC)
print 'monitoring of %s started' % self.path
added_flag = False
# read and process events
while True:
try:
if not added_flag:
# on first iteration, add a watch on path:
# watch path for events handled by mask.
wm.add_watch(self.path, mask)
added_flag = True
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
# ...until c^c signal
print 'stop monitoring...'
# stop monitoring
notifier.stop()
break
except Exception, err:
# otherwise keep on watching
print err
示例13: create_notifier
def create_notifier(topic, instrument, posttroll_port, filepattern,
event_names, monitored_dirs, aliases=None,
tbus_orbit=False, history=0, granule_length=0):
'''Create new notifier'''
# Event handler observes the operations in defined folder
manager = WatchManager()
# Collect mask for events that are monitored
if type(event_names) is not list:
event_names = event_names.split(',')
event_mask = 0
for event in event_names:
try:
event_mask |= getattr(pyinotify, event)
except AttributeError:
LOGGER.warning('Event ' + event + ' not found in pyinotify')
event_handler = EventHandler(topic, instrument,
posttroll_port=posttroll_port,
filepattern=filepattern,
aliases=aliases,
tbus_orbit=tbus_orbit,
history=history,
granule_length=granule_length)
notifier = NewThreadedNotifier(manager, event_handler)
# Add directories and event masks to watch manager
for monitored_dir in monitored_dirs:
manager.add_watch(monitored_dir, event_mask, rec=True)
return notifier
示例14: LinuxFileSysMonitor
class LinuxFileSysMonitor(FileSysMonitor):
"""File system monitor thread"""
def __init__(self, name=None):
super(LinuxFileSysMonitor, self).__init__(name)
self.defaultMask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_MOVED_TO | IN_MOVED_FROM
self.wm = WatchManager()
self.__lock = threading.Lock()
def addWatch(self, path, mask=None):
"""Add watch for path"""
super(LinuxFileSysMonitor, self).addWatch(path, mask)
if not mask:
mask = self.defaultMask
self.wm.add_watch(path, mask, auto_add=True, rec=True)
def run(self):
"""Thread entry"""
super(LinuxFileSysMonitor, self).run()
self.notifier = Notifier(self.wm, EventHandler(None, fsMonitor = self))
while not self.threadStop:
self.processMsg(1)
if self.notifier.check_events(1000):
self.notifier.read_events()
self.notifier.process_events()
def stop(self):
"""Stop watch"""
super(LinuxFileSysMonitor, self).stop()
self.notifier.stop()
示例15: persy_start
def persy_start(self):
"""
initializes the worker thread and notifier
"""
self.log.info("start working")
self.log.setStart()
self.running = True
FLAGS=EventsCodes.ALL_FLAGS
mask = FLAGS['IN_MODIFY'] | FLAGS['IN_DELETE_SELF']|FLAGS['IN_DELETE'] | FLAGS['IN_CREATE'] | FLAGS['IN_CLOSE_WRITE'] | FLAGS['IN_MOVE_SELF'] | FLAGS['IN_MOVED_TO'] | FLAGS['IN_MOVED_FROM'] # watched events
wm = WatchManager()
#addin the watched directories
for watch in self.config['local']['watched']:
wdd = wm.add_watch("%s"%(watch), mask, rec=True, auto_add=True)
#watch for changes of the configurationfile
if self.config['general']['autoshare']:
wdd = wm.add_watch(self.config.getAttribute('CONFIGFILE'), mask, rec=True, auto_add=True)
self.log.debug("init the syncer")
self.worker = TheSyncer(self, self.config, self.log, self.config['remote']['sleep'], self.config['local']['sleep'])
self.log.debug("init the filesystem notifier")
self.notifier = ThreadedNotifier(wm, FileChangeHandler(self.log, self.worker.newEvent))
self.log.resetError()
self.log.debug("starting syncer")
self.worker.start()
self.notifier.start()