工作项目看门狗(记录项目文件以及文件夹的改动)
#!/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...
·

#!/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()更多推荐
所有评论(0)