简答:f = open(... , 'w') 生成FileCreatedEvent、f.flush() 或f.close() 可以生成FileModifiedEvent。所以是的,创建文件通常会同时生成FileCreatedEvent 和FileModifiedEvents。
您是否可以安全地忽略 FileCreatedEvents 取决于您要执行的操作。如果您有兴趣在创建文件时做出反应,那么您需要处理 FileCreatedEvents,并且可能忽略 FileModifiedEvents,因为在修改文件时可能会生成 FileModifiedEvents 而不会生成 FileCreatedEvents。
使用规范的看门狗脚本(如下),一切都应该更清楚了。
长答案:要查看发生了什么,请运行规范的看门狗程序straight from the docs:
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()
从终端:
% mkdir ~/tmp
% cd ~/tmp
% script.py
现在在 Python 解释器中,当您以 w 模式打开文件时:
In [126]: f = open('/home/unutbu/tmp/foobar', 'w')
终端打印
2014-02-05 16:29:34 - <FileCreatedEvent: src_path=/home/unutbu/tmp/foobar>
当你写入文件时看门狗不报告任何事件:
In [127]: f.write('Hi')
但是当你冲洗时,
In [128]: f.flush()
它报告了一个 FileModifiedEvent:
2014-02-05 16:29:55 - <FileModifiedEvent: src_path=/home/unutbu/tmp/foobar>
如果您向文件中写入更多内容:
In [129]: f.write(' there')
类似地,当您关闭文件时会报告 FileModifiedEvent,因为更多的输出被刷新到磁盘:
In [130]: f.close()
2014-02-05 16:30:12 - <FileModifiedEvent: src_path=/home/unutbu/tmp/foobar>