ffmpeg - Creating a watch folder

I’ve seen so many times questions on how to create a watch folder that together with ffmpeg will convert videos from one format to the flv.

So today i felt like trying to create one in Python using inotify.

Inotify is linux kernel only subsystem that provides file system notification. It’s a replacement of dnotify which was a pain in you know where to work with.

I worked with inotify last week doing an image optimizer daemon. I’m writing this in my head and haven’t tested it since i’m at home with no access to a linux box but it should work fine.

You need python, pyinotify, a kernel 2.6.13+ and ofcourse ffmpeg :)

  1. # @author funciton communications <info@funciton.com>
  2. # @version 1.0.0
  3. # Imports
  4. import inotify
  5. import logging
  6. import logging.handlers
  7. import sys
  8. from os import system
  9. # Mask
  10. __flags = inotify.ATTRIB
  11. # Init
  12. if __name__ == "__main__":
  13. path = sys.argv[1]
  14. if len(sys.argv) == 1:
  15. print >> sys.stderr, "Usage: " + sys.argv[0] + " path"
  16. sys.exit(0)
  17. logger = logging.getLogger('watchfolder')
  18. logger.addHandler(logging.handlers.RotatingFileHandler('/var/log/watchfolder.log'))
  19. watcher = inotify.Watcher()
  20. if not watcher.is_watching(path):
  21. print >> sys.stderr, "watching "+ path
  22. watcher.watch(path, __flags)
  23. while (True):
  24. try:
  25. event = watcher.get_next_event()
  26. except Exception:
  27. print "re-scanning"
  28. continue
  29. try:
  30. if event & inotify.ATTRIB:
  31. filename, ext = os.path.splitext(os.path.basename(image))
  32. if ext != ".flv":
  33. # execute ffmpeg
  34. system("ffmpeg -i " + filename + ext + " " + filename + ".flv")
  35. except Exception, er:
  36. print er.strerror
  37. continue

To test it out:

  1. python watchFolder.py /path/to/folder

I’ll test it tomorrow at work if i get better (i’m sick at home) so let me know right away if you find smth which isn’t working fine.

— fernando


comments

Stefan

looks sweet