工作專案看門狗(記錄專案檔案以及資料夾的改動)
阿新 • • 發佈:2018-12-11
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/9/18 18:06 # @Author : qhh # @Site : # @File : pywatchdog.py # @Software: PyCharm # 參考https://www.cnblogs.com/yanzi-meng/p/8618030.html from watchdog.observers import Observer from watchdog.events import * import time import configparser import logging LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s "# 配置輸出日誌格式 DATE_FORMAT = '%Y-%m-%d %H:%M:%S %a ' # 配置輸出時間的格式,注意月份和天數不要搞亂了 logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=r"./test.log" # 有了filename引數就不會直接輸出顯示到控制檯,而是直接寫入檔案 ) def get_cfg_data(cfg_path): cf = configparser.ConfigParser() cf.read(cfg_path, encoding='utf-8-sig') # 獲取所有section,返回值為list secs = cf.sections() print('可輸入資訊列表%s' % secs) # # 獲取db中的所有屬性名 # dboption = cf.options('db') # print(dboption) # # 獲取db中的鍵值對 dbitem = cf.items(secs[0]) print(dict(dbitem)) return dict(dbitem) class FileEventHandler(FileSystemEventHandler): def __init__(self): FileSystemEventHandler.__init__(self) def on_moved(self, event): if event.is_directory: logging.info("directory moved from {0} to {1}".format(event.src_path, event.dest_path)) print("資料夾移動 from {0} to {1}".format(event.src_path, event.dest_path)) else: logging.info("file moved from {0} to {1}".format(event.src_path, event.dest_path)) print("檔案移動 from {0} to {1}".format(event.src_path, event.dest_path)) def on_created(self, event): if event.is_directory: logging.info("資料夾建立:{0}".format(event.src_path)) print("directory created:{0}".format(event.src_path)) else: logging.info("檔案建立:{0}".format(event.src_path)) print("file created:{0}".format(event.src_path)) def on_deleted(self, event): if event.is_directory: logging.info("資料夾刪除:{0}".format(event.src_path)) print("directory deleted:{0}".format(event.src_path)) else: logging.info("檔案刪除:{0}".format(event.src_path)) print("file deleted:{0}".format(event.src_path)) def on_modified(self, event): if event.is_directory: logging.info("資料夾修改:{0}".format(event.src_path)) print("directory modified:{0}".format(event.src_path)) else: logging.info("檔案修改:{0}".format(event.src_path)) print("file modified:{0}".format(event.src_path)) if __name__ == "__main__": observer = Observer() event_handler = FileEventHandler() cfg_data = get_cfg_data(r'pywatchdog.ini') observer.schedule(event_handler, cfg_data['dir_path'], True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()