import os from django.core.management.commands.runserver import Command as BaseCommand from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from django.utils.autoreload import restart_with_reloader class WatchdogEventHandler(FileSystemEventHandler): def __init__(self, command): super().__init__() self.command = command self.allowed_extensions = ['.py'] # 允许处理的文件后缀列表 def on_any_event(self, event): if "__pycache__" in event.src_path: return # 如果事件发生在 __pycache__ 目录中,则直接返回,不做任何处理 if event.is_directory: return file_extension = os.path.splitext(event.src_path)[1] if file_extension not in self.allowed_extensions: return # 如果文件后缀不在允许的列表中,则直接返回,不做任何处理 if event.event_type in ('created', 'deleted', 'modified'): self.command.stdout.write(f"File {event.event_type}: {event.src_path}") # 在此处可以执行你希望在文件变化时执行的操作 restart_with_reloader() class Command(BaseCommand): def handle(self, *args, **options): # 创建 watchdog 观察者对象 observer = Observer() # 创建 watchdog 事件处理器对象 event_handler = WatchdogEventHandler(self) # 监听 Django 项目根目录下的文件变化 observer.schedule(event_handler, '.', recursive=True) # 启动 watchdog 观察者 observer.start() try: # 启动 Django 内置的 runserver 命令 super().handle(*args, **options) finally: # 在 Django 服务停止时停止 watchdog 观察者 observer.stop() observer.join() requires_system_checks = []