首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python-使用watchdog热更新

Python-使用watchdog热更新

作者头像
py3study
发布2020-01-10 14:49:45
1.4K0
发布2020-01-10 14:49:45
举报
文章被收录于专栏:python3python3

直接上代码:

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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档