根據別人寫的方法,對log日誌格式做了處理,有需要的可以收下。
點個讚唄。送人玫瑰,手有餘香。
下面不多說,送上代碼:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import shutil
import sys
import logging
import time
class SynDirTool:
def __init__(self,fromdir,todir):
self.fromdir = fromdir
self.todir = todir
def synDir(self):
return self.__copyDir(self.fromdir,self.todir)
def __copyDir(self,fromdir,todir):
#防止該目錄不存在,創建目錄
self.__mkdir(todir)
count = 0
for filename in os.listdir(fromdir):
if filename.startswith('.'):
continue
fromfile = fromdir + os.sep + filename
tofile = todir + os.sep + filename
if os.path.isdir(fromfile):
count += self.__copyDir(fromfile,tofile)
else:
count += self.__copyFile(fromfile,tofile)
return count
def __copyFile(self,fromfile,tofile):
if not os.path.exists(tofile) :
shutil.copy2(fromfile,tofile)
logging.info("%s 新增%s ==> %s" % (time.strftime("%Y%m%d-%H:%M:%S"),fromfile,tofile))
return 1
fromstat = os.stat(fromfile)
tostat = os.stat(tofile)
if fromstat.st_ctime > tostat.st_ctime:
shutil.copy2(fromfile,tofile)
logging.info("%s 更新%s ==> %s" % (time.strftime("%Y%m%d-%H:%M:%S"),fromfile,tofile))
return 1
return 0
def __mkdir(self,path):
# 去除首位空格
path=path.strip()
# 去除尾部 \ 符號 或者 /
path=path.rstrip(os.sep)
# 判斷路徑是否存在
isExists=os.path.exists(path)
# 判斷結果
if not isExists:
# 如果不存在則創建目錄
logging.info(time.strftime("%Y%m%d-%H:%M:%S")+' '+path+' 目錄創建成功')
# 創建目錄操作函數
os.makedirs(path)
if __name__ == '__main__':
count = 0
srcdir=sys.argv[1]#獲取輸入參數1
descdir=sys.argv[2]#獲取輸入參數2
#logging輸出設置
time_stamp = time.strftime("%Y%m%d_%H%M%S")
logging.basicConfig(filename=time_stamp+'.log', level=logging.INFO)
#開始執行SynDirTool工具類
tool = SynDirTool(srcdir,descdir)
count += tool.synDir()