Python-使用watchdog热更新
短信预约 -IT技能 免费直播动态提醒
直接上代码:
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.class="lazy" data-src_path, event.dest_path))
else:
print("file moved from {0} to {1}".format(event.class="lazy" data-src_path, event.dest_path))
# 文件新建
def on_created(self, event):
if event.is_directory:
print("directory created:{0}".format(event.class="lazy" data-src_path))
else:
self.reload_module(event.class="lazy" data-src_path)
print("file created:{0}".format(event.class="lazy" data-src_path))
# 文件删除
def on_deleted(self, event):
if event.is_directory:
print("directory deleted:{0}".format(event.class="lazy" data-src_path))
else:
print("file deleted:{0}".format(event.class="lazy" data-src_path))
# 文件修改
def on_modified(self, event):
if event.is_directory:
print("directory modified:{0}".format(event.class="lazy" data-src_path))
else:
print("file modified:{0}".format(event.class="lazy" data-src_path))
self.reload_module(event.class="lazy" data-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()
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341