发布时间:2019-07-29 10:01:39编辑:auto阅读(2162)
直接上代码:
import importlib
from watchdog.observers import Observer
from watchdog.events import *
class ScriptEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
# 文件移动
def on_moved(self, event):
if event.is_directory:
print("directory moved from {0} to {1}".format(event.src_path, event.dest_path))
else:
print("file moved from {0} to {1}".format(event.src_path, event.dest_path))
# 文件新建
def on_created(self, event):
if event.is_directory:
print("directory created:{0}".format(event.src_path))
else:
self.reload_module(event.src_path)
print("file created:{0}".format(event.src_path))
# 文件删除
def on_deleted(self, event):
if event.is_directory:
print("directory deleted:{0}".format(event.src_path))
else:
print("file deleted:{0}".format(event.src_path))
# 文件修改
def on_modified(self, event):
if event.is_directory:
print("directory modified:{0}".format(event.src_path))
else:
print("file modified:{0}".format(event.src_path))
self.reload_module(event.src_path)
# 重载模块
def reload_module(self, module_name: str):
module_name = module_name.replace('/', '.')
module_name = module_name.replace('.py', '')
instance = importlib.import_module(module_name)
if instance:
importlib.reload(instance)
observer = Observer()
event_handler = ScriptEventHandler()
# ./test为需要监控的目录
self.observer.schedule(event_handler,'./test', False)
self.observer.start()
上一篇: python中占位符的使用
下一篇: Python _取log的几种方式
47490
45792
36789
34321
28958
25594
24441
19608
19109
17630
5463°
6046°
5568°
5636°
6571°
5374°
5375°
5882°
5853°
7167°