简短的回答: f = open(... , 'w')
生成FileCreatedEvent
,f.flush()
或者f.close()
可以生成FileModifiedEvent
。是的,创建文件通常会同时生成FileCreatedEvent
和FileModifiedEvents
。
是否可以安全地忽略FileCreatedEvents取决于您要执行的操作。如果您有兴趣在创建文件时做出反应,则需要处理FileCreatedEvents,并且可能忽略FileModifiedEvents,因为在修改文件时可以生成FileModifiedEvents,而无需生成FileCreatedEvents。
尝试使用规范的看门狗脚本(如下),并且所有内容都应该更加清晰。
长答案:要查看发生了什么,请直接从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
现在,当您在w
模式下打开文件时,在Python解释器中:
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>