本文整理汇总了Python中pyinotify.ThreadedNotifier类的典型用法代码示例。如果您正苦于以下问题:Python ThreadedNotifier类的具体用法?Python ThreadedNotifier怎么用?Python ThreadedNotifier使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ThreadedNotifier类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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()
示例2: run
def run(self):
"""
Run notify process in loop.
"""
notifier = ThreadedNotifier(self.wm, EventHandler(), read_freq=0, threshold=0, timeout=10)
self._addWatchers()
notifier.loop()
示例3: Notify
class Notify():
def __init__(self):
self.wm = WatchManager()
self.pe = ProcessNotifyEvents()
self.notifier = ThreadedNotifier(self.wm, self.pe)
self.notifier.start()
self.path = None
#thread.start_new_thread(self.jobTask, (self,))
def setNotify(self, path, cbfun):
#print 'setnotify ' + path
if self.path:
self.wm.rm_watch(list(self.wdd.values()))
self.path = path
self.pe.cbfun = cbfun # ugly...
#print sys.getfilesystemencoding()
self.wdd = self.wm.add_watch(self.path,
pyinotify.IN_CREATE |
pyinotify.IN_DELETE |
pyinotify.IN_MOVED_TO |
pyinotify.IN_MOVED_FROM |
pyinotify.IN_MODIFY)
def stop(self):
if self.path:
self.wm.rm_watch(list(self.wdd.values()))
self.notifier.stop()
def notifyThread(self):
while 1:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
示例4: start_watching_disk_file
def start_watching_disk_file(filename, handler):
logger.info("start watching %s" % filename)
wm = WatchManager()
notifier = ThreadedNotifier(wm, PTmp(wm, filename, handler))
notifier.start()
notifiers[filename] = notifier
if os.path.exists(filename):
handler.on_create(filename)
示例5: watch
def watch(self):
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO
self.__wm = WatchManager()
self.__wm.add_watch(os.path.join(self.directory, *self.branch_dir), mask, rec = True)
notifier = ThreadedNotifier(self.__wm, self.process_event)
notifier.start()
示例6: __watch_thread
def __watch_thread(self, root_lst, sync_list, cond, eventq):
"""
初始化客户端监控文件变化的同步线程,根据同步的根目录列表和
需要同步的文件目录白名单,获取需要监控的目录列表以及监控排除的文件列表添加到INotifier中
@param root_lst: 监控的根目录列表
@type root_lst: tuple
@param sync_list: 需要同步的文件和目录的列表
@type sync_list: tuple
@param cond: 线程同步条件变量
@type cond: threading.Condition
@param eventq: 保存文件变化的事件队列
@type eventq: pyinotify.Event
@return: 初始化后的监控线程
@rtype: pyinotify.ThreadedNotifier
"""
wm = WatchManager()
mask = IN_DELETE | IN_CLOSE_WRITE | IN_CREATE | IN_MOVED_FROM | IN_MOVED_TO
thread_notifier = ThreadedNotifier(wm,
EventHandler(cond=cond, eventq=eventq,
sync_list=sync_list),
read_freq=10, timeout=9)
thread_notifier.coalesce_events() # Enable coalescing of events
watch_lst = [] # INotifier watch direcory list
exclude_lst = [] # INotifier exclude directory list
LOGGER.debug('root:%s', str(root_lst))
LOGGER.debug('sublist:%s', str(sync_list))
for root_path in root_lst:
# add root directory to watch list
watch_lst.append(root_path['name'])
if not root_path['is_all']:
# get exclude sub direcory list
for dirpath, _, _ in os.walk(root_path['name']):
if dirpath != root_path['name']:
for file_path in sync_list:
is_exclude = True
if file_path.startswith(dirpath) \
or dirpath.startswith(file_path):
# 遍历的目录为同步列表文件的父目录,
# 或者同步文件列表下的子目录,都不添加到排除目录列表
LOGGER.debug('dirpath:%s', dirpath)
LOGGER.debug('file_path:%s', file_path)
is_exclude = False
break
if is_exclude:
exclude_lst.append(dirpath)
LOGGER.debug('watchlist:%s', str(watch_lst))
LOGGER.debug('excludelist:%s', str(exclude_lst))
excl = ExcludeFilter(exclude_lst)
# 设置受监视的事件,(rec=True, auto_add=True)为递归处理
wm_dict = wm.add_watch(watch_lst, mask, rec=True, auto_add=True,
exclude_filter=excl)
LOGGER.debug('client monitor lst:%s', str(wm_dict))
return thread_notifier
示例7: PhotoWatcher
class PhotoWatcher(ProcessEvent):
MASK = (EventsCodes.ALL_FLAGS['IN_DELETE'] |
EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'] |
EventsCodes.ALL_FLAGS['IN_MOVED_FROM'] |
EventsCodes.ALL_FLAGS['IN_MOVED_TO'])
def __init__(self, db, walker, root):
self.root = root
self.db = db
self.walker = walker
self.wm = WatchManager()
self.wdds = []
def Watch(self):
self.notifier = ThreadedNotifier(self.wm, self)
self.notifier.start()
self.wdds.append(self.wm.add_watch(self.root, self.MASK, rec=True))
# add soft link sub-folders
for dirname, dirnames, _filenames in os.walk(self.root, followlinks=True):
for d in dirnames:
path = os.path.join(dirname, d)
if os.path.islink(path):
self.wdds.append(
self.wm.add_watch(os.path.realpath(path), self.MASK, rec=True))
def Stop(self):
self.notifier.stop()
def process_IN_DELETE(self, event):
self.db.DeletePhoto(os.path.join(event.path, event.name))
def process_IN_MOVED_FROM(self, event):
self.process_IN_DELETE(event)
def process_IN_MOVED_TO(self, event):
full_path = os.path.join(event.path, event.name)
try:
meta = self.walker.ReadMetadata(full_path)
except Exception:
return
self.db.StorePhoto(full_path, meta)
def process_IN_CLOSE_WRITE(self, event):
full_path = os.path.join(event.path, event.name)
try:
meta = self.walker.ReadMetadata(full_path)
except Exception:
return
if self.db.HasPhoto(full_path):
self.db.UpdatePhoto(full_path, meta)
else:
self.db.StorePhoto(full_path, meta)
示例8: __init__
class FileEvent:
def __init__(self, eventHandler):
self.logger = logging.getLogger('FileEvent')
self.wm = WatchManager()
self.watches = dict()
# Set the flags of the events that are to be listened to
FLAGS = EventsCodes.ALL_FLAGS
self.mask = FLAGS['IN_CREATE'] | FLAGS['IN_DELETE'] | FLAGS['IN_MODIFY'] | FLAGS['IN_DELETE_SELF']
# Set-up notifier
self.notifier = ThreadedNotifier(self.wm, EventProcessor(eventHandler))
def startNotifyLoop(self):
self.notifier.start()
def stopNotifyLoop(self):
self.notifier.stop()
def addWatches(self, paths, mask=None):
added_watches = dict()
for path in paths:
added_watches.update(self.addWatch(path, mask))
return added_watches
# Also monitors all sub-directories of the given directory and automatically adds newly
# created directories to watch.
# TODO should be able to add files as well, but doesn't work atm
def addWatch(self, path, mask=None):
if mask is None:
mask = self.mask
added_watches = self.wm.add_watch(path, mask, rec=True, auto_add=True)
self.watches.update(added_watches)
return added_watches
def removeWatch(self, path):
watch_descriptor = self.wm.get_wd(path)
if watch_descriptor is not None:
result = self.wm.rm_watch(watch_descriptor, rec=True)
# Remove the no longer active watches from the current watches dictionary
for key, value in self.watches.items():
if value in result:
del self.watches[key]
else:
result = None
return result
def getWatches(self):
return self.watches
示例9: schedule
def schedule(self, name, event_handler, *paths):
"""Schedules monitoring."""
#from pyinotify import PrintAllEvents
#dispatcher = PrintAllEvents()
dispatcher = _ProcessEventDispatcher(event_handler=event_handler)
notifier = ThreadedNotifier(self.wm, dispatcher)
self.notifiers.add(notifier)
for path in paths:
if not isinstance(path, str):
raise TypeError(
"Path must be string, not '%s'." % type(path).__name__)
descriptors = self.wm.add_watch(path, ALL_EVENTS, rec=True, auto_add=True)
self.name_to_rule[name] = _Rule(name, notifier, descriptors)
notifier.start()
示例10: live
def live(path, tv):
chromedriver = os.path.join(os.path.split(os.path.realpath(__file__))[0],\
'chromedriver')
os.environ['webdriver.chrome.driver'] = chromedriver
browsers = [ getattr(webdriver, browser.title())() \
for browser in [s.lower() for s in tv]]
wm = WatchManager()
notifier = ThreadedNotifier(wm, ProcessDir(browsers))
notifier.start()
print('watching %s' % os.path.abspath(path))
mask = IN_MODIFY
wdd = wm.add_watch(path, mask, rec=True)
示例11: setup_inotify
def setup_inotify(self):
if pyinotify is None:
return False
watch_manager = WatchManager()
result = watch_manager.add_watch(self.__status_file, IN_MODIFY)[self.__status_file] > 0
if result:
global notifier
def notify_cb(event):
glib.idle_add(self.check_status_cb)
notifier = ThreadedNotifier(watch_manager, notify_cb)
notifier.start()
return result
示例12: 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()
示例13: enabled
def enabled( self ):
if not self.running :
self.wm = WatchManager()
# the event handler will do the actual event processing,
# see the ALE class below for details
self.event_handler = self.ALE( self )
# we'll use a threaded notifier flagged as a daemon thread
# so that it will stop when QL does
self.tn = ThreadedNotifier( self.wm, self.event_handler )
self.tn.daemon = True
self.tn.start()
# mask for watched events:
FLAGS=EventsCodes.ALL_FLAGS
mask = FLAGS['IN_DELETE'] | FLAGS['IN_CLOSE_WRITE']\
| FLAGS['IN_MOVED_FROM'] | FLAGS['IN_MOVED_TO']
# watch paths in scan_list:
for path in self.scan_list():
log ( 'Adding watch: for ' + path )
self.wm.add_watch( path, mask, rec=True )
self.running = True
示例14: __init__
def __init__(self, makeRunView):
self.wm = WatchManager()
self.eh = EventHandler(makeRunView)
self.notifier = ThreadedNotifier(self.wm, self.eh)
self.notifier.start()
# Watched events
self.mask = IN_DELETE | IN_CREATE | IN_CLOSE_WRITE
示例15: main
def main():
# Add a dummy message to the queue:
add_msg( MsgTypes.Initialise )
# Setup the HTTP server:
SocketServer.TCPServer.allow_reuse_address = True
HOST, PORT = "localhost", 9000
server = ThreadedHTTPServer((HOST, PORT), MyTCPHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
# Setup the heartbeat:
heartbeat_thread = threading.Thread(target=heartbeat_messages)
heartbeat_thread.daemon = True
heartbeat_thread.start()
# Setup pyinotify so files are being watched:
wm = WatchManager()
notifier = ThreadedNotifier(wm, PTmp())
notifier.start()
mask = EventsCodes.ALL_FLAGS['IN_DELETE'] | EventsCodes.ALL_FLAGS['IN_CREATE'] | EventsCodes.ALL_FLAGS['IN_ATTRIB'] |EventsCodes.ALL_FLAGS['IN_MODIFY']# watched events
#mask = EventsCodes.ALL_FLAGS['IN_DELETE'] | EventsCodes.ALL_FLAGS['IN_CREATE'] | EventsCodes.ALL_FLAGS['IN_MODIFY']# watched events
wdd = wm.add_watch('../sentry.py', mask, rec=True)
wdd = wm.add_watch('../', mask, rec=True)
try:
while True:
time.sleep(5)
except:
# Turn off pyinotify:
notifier.stop()
print 'Exception caught: shutting down connections'
add_msg(MsgTypes.Shutdown)
time.sleep(0.5)
print 'Terminating...'
raise