Search code examples
pythonregexpyinotify

Unable to use regex with pyinotify


It's possible to use a regex with inotify shell command, but not with pyinotify. I could get the list of directories using the regex and pass it to add_watch, but, the folders "Do*" are dynamic, in the sense that they are created and destroyed very often and hence, creating a rigid list and passing it to the add_watch function would be inaccurate.

I've tried to compile the regex and pass it to add_watch and it doesn't work, probably because it expects a string or list of strings.

import pyinotify,subprocess,re
def onChange(ev):
  subprocess.run("echo 'changed'", shell = True)

wm = pyinotify.WatchManager()
regex_dir = re.compile('/var/run/shm/Do*/updates/ab*.xml')
wm.add_watch(regex_dir, pyinotify.IN_CLOSE_WRITE , onChange)
notifier = pyinotify.Notifier(wm)
notifier.loop()

I would like to pass a regex to add_watch function of pyinotify without having to create a rigid list and then pass that since the directory contents would vary.


Solution

  • WatchManager.add_watch accepts a do_glob option that allows to perform globbing on pathname.

    You pass a unicode str and not a regex object for the path argument.

    dir_glob = '/var/run/shm/Do*/updates/ab*.xml'
    wm.add_watch(dir_glob, pyinotify.IN_CLOSE_WRITE, onChange, do_glob=True)