通过python写一个程序,监控指定文件夹内文件的增,删,改情况,需要输出删除者,所删除的文件,执行删除操作的程序名等信息
时间: 2023-05-24 16:04:45 浏览: 102
可以使用Python模块watchdog来实现文件夹监控,通过监控事件来判断文件的增删改情况。使用psutil模块获取删除操作的程序名。
下面是一个代码示例,可以根据需要进行修改:
``` python
import time
import os
import psutil
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
print(f"Created: {event.src_path}")
def on_deleted(self, event):
filename = os.path.basename(event.src_path)
print(f"Deleted: {event.src_path}")
self.show_delete_process(filename)
def on_modified(self, event):
print(f"Modified: {event.src_path}")
def on_moved(self, event):
print(f"Moved: {event.src_path} to {event.dest_path}")
def show_delete_process(self, filename):
for proc in psutil.process_iter(['pid', 'name']):
try:
for f in proc.open_files():
if os.path.basename(f.path) == filename:
print(f"Deleted by {proc.name()}: {filename}")
return
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
print(f"Deleted: {filename} (unknown process)")
if __name__ == "__main__":
path = "/path/to/watch"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
print(f"Watching {path} for changes...")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
```
运行后,程序会监控指定路径下的文件夹,并输出文件的增删改情况。删除操作会输出删除者和被删除的文件,并通过psutil模块获取删除操作的程序名。
阅读全文