-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_monitor.py
55 lines (41 loc) · 1.37 KB
/
file_monitor.py
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
监控指定目录下的文件,并删除符合条件的文件。
"""
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def should_be_deleted(path: str):
return False
class Watcher:
DIRECTORY_TO_WATCH = "/tmp/" # 指定要监控的目录
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
self.observer.start()
try:
while True:
time.sleep(0.1)
except:
self.observer.stop()
print("Observer Stopped")
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
# 检测到新文件创建
print(f"Received created event - {event.src_path}.")
# 如果文件名符合删除条件,则删除该文件
if should_be_deleted(event.src_path): # 替换为您要删除的特定文件名
os.remove(event.src_path)
print(f"Deleted file - {event.src_path}.")
if __name__ == '__main__':
w = Watcher()
w.run()