以前的简单版本 通过python中的os模块操作系统命令 详情可参考:Python实现一行代码推本地git到远程仓库
升级版本 本次加入了监听文件修改功能 这样脚本只需在后台运行,即可检测到对应的文件夹中的内容是否变化
如果变化,则调用自动push函数,即可实现推本地仓库到远程中
依赖库的配置 这里我们需要用到一个库watchdog
关于它的安装和使用可以参考:python中文件变化监控-watchdog
代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 from watchdog.observers import Observerfrom watchdog.events import *import timeimport osdef push (change ): print('-' *76 ) os.system('git add .' ) os.system('git commit -m\"auto' +change+'\"' ) os.system('git push -u origin master' ) print('-' *76 ) class FileEventHandler (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)) push("文件移动: {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 : print("file created:{0}" .format (event.src_path)) push("创建文件:{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)) push("删除文件:{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)) push("文件修改:{0}" .format (event.src_path)) if __name__ == "__main__" : observer = Observer() event_handler = FileEventHandler() dis_dir = "./_posts/" observer.schedule(event_handler, dis_dir, True ) observer.start() try : while True : time.sleep(1 ) except KeyboardInterrupt: observer.stop() observer.join()