Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reloader.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. import os
  6. import re
  7. import sys
  8. import time
  9. import threading
  10. class Reloader(threading.Thread):
  11. def __init__(self, extra_files=None, interval=1, callback=None):
  12. super(Reloader, self).__init__()
  13. self.setDaemon(True)
  14. self._extra_files = set(extra_files or ())
  15. self._extra_files_lock = threading.RLock()
  16. self._interval = interval
  17. self._callback = callback
  18. def add_extra_file(self, filename):
  19. with self._extra_files_lock:
  20. self._extra_files.add(filename)
  21. def get_files(self):
  22. fnames = [
  23. re.sub('py[co]$', 'py', module.__file__)
  24. for module in list(sys.modules.values())
  25. if hasattr(module, '__file__')
  26. ]
  27. with self._extra_files_lock:
  28. fnames.extend(self._extra_files)
  29. return fnames
  30. def run(self):
  31. mtimes = {}
  32. while True:
  33. for filename in self.get_files():
  34. try:
  35. mtime = os.stat(filename).st_mtime
  36. except OSError:
  37. continue
  38. old_time = mtimes.get(filename)
  39. if old_time is None:
  40. mtimes[filename] = mtime
  41. continue
  42. elif mtime > old_time:
  43. if self._callback:
  44. self._callback(filename)
  45. time.sleep(self._interval)