Guest User

Untitled

a guest
Nov 20th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*-coding:utf-8-*-
  3.  
  4. # usage:
  5. # ./Watchdog.py <subfile> <commands>
  6.  
  7. # This script takes a <subfile> file and a list of <commands> which it immediately
  8. # executes in a subprocess.
  9. # It kills the subprocess and relaunches it whenever the file changes.
  10. #
  11. # If you accidentally introduce an error into the <subfile>, just fix that error
  12. # and save the file again, and <commands> will be executed.
  13. # Note that the subprocess shares the console with this process,
  14. # therefore you will see its output.
  15.  
  16. import sys
  17. import time
  18. import subprocess
  19. # import logging
  20. import os
  21. import watchdog
  22. import watchdog.events
  23. import watchdog.observers
  24. import psutil
  25. import signal
  26.  
  27. process = None
  28. subfile = sys.argv[1]
  29. command = ' '.join(sys.argv[2:])
  30.  
  31.  
  32. def launch():
  33. global process
  34. process = subprocess.Popen(command, shell=True)
  35. print("process with pid of {0} created".format(process.pid))
  36.  
  37.  
  38. def samefile(a, b):
  39. return os.stat(a) == os.stat(b)
  40.  
  41.  
  42. def kill_or_do_nothing():
  43. global process
  44. try: # Process might already have terminated
  45. process = psutil.Process(pid=process.pid)
  46. for proc in process.children(recursive=True):
  47. proc.kill()
  48. process.kill()
  49. except Exception as E:
  50. print("couldn't destroy process, reason:\n\t",
  51. str(E))
  52.  
  53.  
  54. class Modified(watchdog.events.FileSystemEventHandler):
  55. def on_modified(self, event):
  56. if subfile not in event.src_path:
  57. return
  58. if not samefile(event.src_path, subfile):
  59. return
  60.  
  61. print('<<', subfile, '>> modified, will restart\n')
  62. kill_or_do_nothing()
  63. launch()
  64.  
  65.  
  66. class GracefulKiller():
  67. kill_now = False
  68.  
  69. def __init__(self):
  70. signal.signal(signal.SIGINT, self.exit_gracefully)
  71. signal.signal(signal.SIGTERM, self.exit_gracefully)
  72.  
  73. def __str__(self):
  74. print(self.kill_now)
  75.  
  76. def exit_gracefully(self, signum, frame):
  77. self.kill_now = True
  78.  
  79.  
  80. def main():
  81. global killer
  82.  
  83. observer = watchdog.observers.Observer()
  84. observer.schedule(Modified(), '.')
  85. observer.start()
  86.  
  87. launch()
  88. kill_or_do_nothing()
  89.  
  90. # Idle forever, listening on Modified.on_modified
  91. while killer.kill_now is False:
  92. time.sleep(1)
  93.  
  94.  
  95. if __name__ == '__main__':
  96. global killer
  97. killer = GracefulKiller()
  98. main()
  99. print("Watchdog exited successfully")
Add Comment
Please, Sign In to add comment