watch.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  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(self.cwd, 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. rc = proc.returncode
  41. if rc != 0:
  42. print("Error?")
  43. return
  44. d.insert_raw(file_info(out_fname))
  45. def process_IN_CLOSE_WRITE(self, event):
  46. if not event.pathname.endswith(self.extension):
  47. return
  48. print(event.mask, event.maskname, event.pathname)
  49. self._run_cmd(event.pathname)
  50. def auto_compile(path, extension, cmd):
  51. wm = pyinotify.WatchManager()
  52. handler = OnWriteHandler(cwd=path, extension=extension, cmd=cmd)
  53. notifier = pyinotify.Notifier(wm, default_proc_fun=handler)
  54. wm.add_watch(path, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
  55. print('==> Start monitoring %s' % path)
  56. notifier.loop()
  57. if __name__ == '__main__':
  58. if len(sys.argv) < 3:
  59. print ("Command line error: missing argument(s).")
  60. sys.exit(1)
  61. # Required arguments
  62. path = sys.argv[1]
  63. extension = sys.argv[2]
  64. # Optional argument
  65. cmd = 'ls'
  66. if len(sys.argv) == 4:
  67. cmd = sys.argv[3]
  68. # Blocks monitoring
  69. auto_compile(path, extension, cmd)