-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-file-watcher.py
More file actions
67 lines (56 loc) · 1.99 KB
/
simple-file-watcher.py
File metadata and controls
67 lines (56 loc) · 1.99 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
"""Watch a directory for file system changes using polling."""
import time
import argparse
from pathlib import Path
from datetime import datetime
def scan(directory: Path, recursive: bool) -> dict[str, float]:
snapshot: dict[str, float] = {}
files = directory.rglob("*") if recursive else directory.glob("*")
for path in files:
if path.is_file():
try:
snapshot[str(path)] = path.stat().st_mtime
except OSError:
pass
return snapshot
def watch(directory: str, interval: float, recursive: bool) -> None:
root = Path(directory).resolve()
print(
f"Watching {root} (interval: {interval}s, recursive: {recursive})", flush=True
)
previous = scan(root, recursive)
while True:
time.sleep(interval)
current = scan(root, recursive)
ts = datetime.now().strftime("%H:%M:%S")
for path in sorted(set(current) - set(previous)):
print(f"[{ts}] CREATED {path}", flush=True)
for path in sorted(set(previous) - set(current)):
print(f"[{ts}] DELETED {path}", flush=True)
for path in sorted(set(current) & set(previous)):
if current[path] != previous[path]:
print(f"[{ts}] MODIFIED {path}", flush=True)
previous = current
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Watch a directory for file changes.")
parser.add_argument(
"directory",
nargs="?",
default=".",
help="Directory to watch (default: current)",
)
parser.add_argument(
"-i",
"--interval",
type=float,
default=1.0,
help="Poll interval in seconds (default: 1.0)",
)
parser.add_argument(
"--no-recursive", action="store_true", help="Do not watch subdirectories"
)
args = parser.parse_args()
try:
watch(args.directory, args.interval, not args.no_recursive)
except KeyboardInterrupt:
print("\nStopped.")