watch.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. #
  3. # Usage:
  4. # ./autocompile.py path ext1
  5. #
  6. # Blocks monitoring |path| and its subdirectories for modifications on
  7. # files ending with suffix |extk|. Run |cmd| each time a modification
  8. # is detected. |cmd| is optional and defaults to 'make'.
  9. import subprocess
  10. import sys
  11. import os
  12. import pyinotify
  13. from db import db,file_info
  14. from constants import RAW_PATH,INCOMING_PATH
  15. from subprocess import Popen,PIPE
  16. class OnWriteHandler(pyinotify.ProcessEvent):
  17. def my_init(self, cwd, extension, cmd):
  18. self.cwd = cwd
  19. self.extension = extension
  20. self.cmd = cmd
  21. def _run_cmd(self,path):
  22. print('==> Modification detected')
  23. d=db()
  24. out_fname=os.path.join(RAW_PATH, os.path.basename(path).replace('flv','mp4'))
  25. in_fname=os.path.join(INCOMING_PATH, path)
  26. if os.path.isfile(out_fname):
  27. #exists
  28. return
  29. process=[ 'ffmpeg',
  30. '-loglevel', 'error',
  31. '-i', in_fname,
  32. '-c', 'copy',
  33. '-movflags', '+faststart',
  34. '-f','mp4',
  35. out_fname
  36. ]
  37. print(" ".join(process))
  38. proc=Popen(process, universal_newlines=True)
  39. proc.wait()
  40. d.insert_raw(file_info(out_fname))
  41. def process_IN_MODIFY(self, event):
  42. if not event.pathname.endswith(self.extension):
  43. return
  44. #print(event)
  45. print(event.mask, event.maskname, event.pathname)
  46. #self._run_cmd(event.pathname)
  47. def auto_compile(path, extension, cmd):
  48. wm = pyinotify.WatchManager()
  49. handler = OnWriteHandler(cwd=path, extension=extension, cmd=cmd)
  50. notifier = pyinotify.Notifier(wm, default_proc_fun=handler)
  51. wm.add_watch(path, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
  52. print('==> Start monitoring %s (type c^c to exit)' % path)
  53. notifier.loop()
  54. if __name__ == '__main__':
  55. if len(sys.argv) < 3:
  56. print ("Command line error: missing argument(s).")
  57. sys.exit(1)
  58. # Required arguments
  59. path = sys.argv[1]
  60. extension = sys.argv[2]
  61. # Optional argument
  62. cmd = 'ls'
  63. if len(sys.argv) == 4:
  64. cmd = sys.argv[3]
  65. # Blocks monitoring
  66. auto_compile(path, extension, cmd)