Python watchdog changed and events duplicated

Running on Ubuntu, every time I create a file, I get a modified and created event.

Is it by design or am I something wrong?

I am using an event handler class PatternMatchingEventHandler

event_handler = MediaFileHandler(ignore_directories=True) 
observer = Observer() 
observer.schedule(event_handler, path=directory, recursive=True) 
observer.start()

If this is the correct behavior, can I safely ignore the generated event?

+4
source share
1 answer

Short answer: f = open(... , 'w')creates FileCreatedEvent, f.flush()or f.close()can generate a FileModifiedEvent. So yes, file creation often generates both FileCreatedEvent, and FileModifiedEvents.

, FileCreatedEvents, , . , , FileCreatedEvents , , FileModifiedEvents, FileModifiedEvents, FileCreatedEvents.

script (), .


: , , canonical watchdog :

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>
+9

Source: https://habr.com/ru/post/1525489/


All Articles