read_directory_changes.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
  5. # Copyright 2012 Google, Inc.
  6. # Copyright 2014 Thomas Amland
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. import threading
  20. import os.path
  21. import time
  22. from watchdog.events import (
  23. DirCreatedEvent,
  24. DirMovedEvent,
  25. DirModifiedEvent,
  26. FileCreatedEvent,
  27. FileDeletedEvent,
  28. FileMovedEvent,
  29. FileModifiedEvent,
  30. generate_sub_moved_events,
  31. generate_sub_created_events,
  32. )
  33. from watchdog.observers.api import (
  34. EventEmitter,
  35. BaseObserver,
  36. DEFAULT_OBSERVER_TIMEOUT,
  37. DEFAULT_EMITTER_TIMEOUT
  38. )
  39. from watchdog.observers.winapi import (
  40. read_events,
  41. get_directory_handle,
  42. close_directory_handle,
  43. )
  44. # HACK:
  45. WATCHDOG_TRAVERSE_MOVED_DIR_DELAY = 1 # seconds
  46. class WindowsApiEmitter(EventEmitter):
  47. """
  48. Windows API-based emitter that uses ReadDirectoryChangesW
  49. to detect file system changes for a watch.
  50. """
  51. def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT):
  52. EventEmitter.__init__(self, event_queue, watch, timeout)
  53. self._lock = threading.Lock()
  54. self._handle = None
  55. def on_thread_start(self):
  56. self._handle = get_directory_handle(self.watch.path)
  57. def on_thread_stop(self):
  58. if self._handle:
  59. close_directory_handle(self._handle)
  60. def _read_events(self):
  61. return read_events(self._handle, self.watch.path, self.watch.is_recursive)
  62. def queue_events(self, timeout):
  63. winapi_events = self._read_events()
  64. with self._lock:
  65. last_renamed_src_path = ""
  66. for winapi_event in winapi_events:
  67. src_path = os.path.join(self.watch.path, winapi_event.src_path)
  68. if winapi_event.is_renamed_old:
  69. last_renamed_src_path = src_path
  70. elif winapi_event.is_renamed_new:
  71. dest_path = src_path
  72. src_path = last_renamed_src_path
  73. if os.path.isdir(dest_path):
  74. event = DirMovedEvent(src_path, dest_path)
  75. if self.watch.is_recursive:
  76. # HACK: We introduce a forced delay before
  77. # traversing the moved directory. This will read
  78. # only file movement that finishes within this
  79. # delay time.
  80. time.sleep(WATCHDOG_TRAVERSE_MOVED_DIR_DELAY)
  81. # The following block of code may not
  82. # obtain moved events for the entire tree if
  83. # the I/O is not completed within the above
  84. # delay time. So, it's not guaranteed to work.
  85. # TODO: Come up with a better solution, possibly
  86. # a way to wait for I/O to complete before
  87. # queuing events.
  88. for sub_moved_event in generate_sub_moved_events(src_path, dest_path):
  89. self.queue_event(sub_moved_event)
  90. self.queue_event(event)
  91. else:
  92. self.queue_event(FileMovedEvent(src_path, dest_path))
  93. elif winapi_event.is_modified:
  94. cls = DirModifiedEvent if os.path.isdir(src_path) else FileModifiedEvent
  95. self.queue_event(cls(src_path))
  96. elif winapi_event.is_added:
  97. isdir = os.path.isdir(src_path)
  98. cls = DirCreatedEvent if isdir else FileCreatedEvent
  99. self.queue_event(cls(src_path))
  100. if isdir and self.watch.is_recursive:
  101. # If a directory is moved from outside the watched folder to inside it
  102. # we only get a created directory event out of it, not any events for its children
  103. # so use the same hack as for file moves to get the child events
  104. time.sleep(WATCHDOG_TRAVERSE_MOVED_DIR_DELAY)
  105. sub_events = generate_sub_created_events(src_path)
  106. for sub_created_event in sub_events:
  107. self.queue_event(sub_created_event)
  108. elif winapi_event.is_removed:
  109. self.queue_event(FileDeletedEvent(src_path))
  110. elif winapi_event.is_removed_self:
  111. self.stop()
  112. class WindowsApiObserver(BaseObserver):
  113. """
  114. Observer thread that schedules watching directories and dispatches
  115. calls to event handlers.
  116. """
  117. def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT):
  118. BaseObserver.__init__(self, emitter_class=WindowsApiEmitter,
  119. timeout=timeout)