-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileWatcher.py
More file actions
76 lines (72 loc) · 2.2 KB
/
Copy pathFileWatcher.py
File metadata and controls
76 lines (72 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# BEGIN
#
# IMPORT necessary modules:
# - time
# - logging
# - watchdog.observers.Observer
# - watchdog.events.FileSystemEventHandler
# - os
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
# SETUP logging:
# - Define log file name
# - Configure logging to write to both file and console
# - Set format and logging level
log_file_name = "log.txt"
logging.basicConfig(filename=log_file_name,level=logging.INFO,datefmt="%d/%m/%Y %I:%M:%S %p")
# DEFINE FileEventHandler class (inherits from FileSystemEventHandler):
#
# METHOD on_created(event):
# IF event is not a directory:
# Log "File created" with event path
#
# METHOD on_modified(event):
# IF event is not a directory:
# Log "File modified" with event path
#
# METHOD on_deleted(event):
# IF event is not a directory:
# Log "File deleted" with event path
class FileWatcher(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
logging.log(logging.INFO, msg="file created {event.src_path}")
# DEFINE start_watching(directory_path):
#
# IF directory_path does not exist:
# Log error and RETURN
#
# CREATE instance of FileEventHandler
# CREATE Observer
# Schedule observer to watch directory_path (non-recursively)
# START observer
# Log "Started watching"
#
# TRY:
# LOOP forever:
# Sleep for a short time (e.g., 1 second)
# EXCEPT KeyboardInterrupt:
# STOP observer
# Log "Stopped watching"
# JOIN observer thread
def start_watching(directory_path):
event_handler = FileWatcher()
observer = Observer()
observer.schedule(event_handler, path=directory_path, recursive=True)
observer.start()
logging.log(logging.INFO, msg="file watcher started")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
logging.log(logging.INFO, msg="file watcher stopped")
observer.join()
# IN MAIN block:
# SET folder_to_watch (e.g., "C:\\your\\path")
# CALL start_watching with folder_to_watch
#
# END