我正在使用Watchdog在 Python 中创建一个程序,该程序监视一组文件并根据更改采取措施。我将他们网站上的确切示例放在一个文件中:
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
然后,我注意到了一些奇怪的事情。我以相同的方式(使用pip2 install watchdog
and pip3 install watchdog
)同时为 Python 2 和 Python 3 安装了看门狗。但是,当我在 Python 2 和 3 中运行程序并对每个程序进行一次相同的修改时,会发生这种情况:
$ python2 watch_test.py
2015-09-30 11:18:32 - Modified file: ./watch_test.py
$ python3 watch_test.py
2015-09-30 11:18:39 - Modified file: ./watch_test.py
2015-09-30 11:18:39 - Modified file: ./watch_test.py
2015-09-30 11:18:39 - Modified file: ./watch_test.py
我想知道是什么可能导致这种行为以及我该如何解决它。
这个问题不是重复的:
- python watchdog 运行不止一次;事件都是一样的
- Python 看门狗重复事件;该错误仅发生在 Python 3 上,而不发生在 Python 2 上。