首页 > 代码库 > python3 监控代码变化 自动重启 提高开发效率
python3 监控代码变化 自动重启 提高开发效率
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = ‘Michael Liao‘ import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s): print(‘[Monitor] %s‘ % s) class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn): super(MyFileSystemEventHander, self).__init__() self.restart = fn def on_any_event(self, event): if event.src_path.endswith(‘.py‘): log(‘Python source file changed: %s‘ % event.src_path) self.restart() command = [‘echo‘, ‘ok‘] process = None def kill_process(): global process if process: log(‘Kill process [%s]...‘ % process.pid) process.kill() process.wait() log(‘Process ended with code %s.‘ % process.returncode) process = None def start_process(): global process, command log(‘Start process %s...‘ % ‘ ‘.join(command)) process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) def restart_process(): kill_process() start_process() def start_watch(path, callback): observer = Observer() observer.schedule(MyFileSystemEventHander(restart_process), path, recursive=True) observer.start() log(‘Watching directory %s...‘ % path) start_process() try: while True: time.sleep(0.5) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == ‘__main__‘: argv = sys.argv[1:] if not argv: print(‘Usage: ./pymonitor your-script.py‘) exit(0) if argv[0] != ‘python3‘: argv.insert(0, ‘python3‘) command = argv path = os.path.abspath(‘.‘) start_watch(path, None)
保存未check.py
启动监控 执行run.py
python3 check.py run.py
当目录下面代码有变化时会重启run.py
python3 监控代码变化 自动重启 提高开发效率
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。