I want to monitor a dir , and the dir has sub dirs and in subdir there are somes files with .md
. (maybe there are some other files, such as *.swp...)
I only want to monitor the .md files, I have read the doc, and there is only a ExcludeFilter
, and in the issue : https://github.com/seb-m/pyinotify/issues/31 says, only dir can be filter but not files.
Now what I do is to filter in process_*
functions to check the event.name
by fnmatch
.
So if I only want to monitor the specified suffix files, is there a better way? Thanks.
This is the main code I have written:
!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyinotify
import fnmatch
def suffix_filter(fn):
suffixes = ["*.md", "*.markdown"]
for suffix in suffixes:
if fnmatch.fnmatch(fn, suffix):
return False
return True
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
if not suffix_filter(event.name):
print "Creating:", event.pathname
def process_IN_DELETE(self, event):
if not suffix_filter(event.name):
print "Removing:", event.pathname
def process_IN_MODIFY(self, event):
if not suffix_filter(event.name):
print "Modifing:", event.pathname
def process_default(self, event):
print "Default:", event.pathname
I think you basically have the right idea, but that it could be implemented more easily.
The
ProcessEvent
class in the pyinotify module already has a hook you can use to filter the processing of events. It's specified via an optionalpevent
keyword argument given on the call to the constructor and is saved in the instance'sself.pevent
attribute. The default value isNone
. It's value is used in the class'__call__()
method as shown in the following snippet from thepyinotify.py
source file:So you could use it only allow events for files with certain suffixes (aka extensions) with something like this: