# -*- coding: utf-8 -*- """ Created on Wed Dec 30 20:22:43 2020 @author: Tj """ import os import time import shutil from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class CreatedHandler(FileSystemEventHandler): def on_created(self, event): if event.is_directory: return else: file_done = False file_size = -1 while file_size != os.path.getsize(event.src_path): file_size = os.path.getsize(event.src_path) time.sleep(0.5) while not file_done: # noinspection PyBroadException try: os.rename(event.src_path, event.src_path) file_done = True except Exception: return True relt_path = event.src_path.replace(sourcepath, destinationpath) f = open('A350GAS-COPY.log', 'a') print(('拷贝目录:' + relt_path+'拷贝时间:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())), file=f) print('拷贝目录:' + relt_path+'拷贝时间:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) shutil.copy2(event.src_path, relt_path) def sync(sourcepath, destinationpath): print("synchronize'%s' >> '%s'..." % (sourcepath, destinationpath)) print("=" * 50) sync_file_count = 0 sync_file_size = 0 for root, dirs, files in os.walk(sourcepath): relative_path = root.replace(sourcepath, "") if len(relative_path) > 0 and relative_path[0] in ("/", "\\"): relative_path = relative_path[1:] dist_path = os.path.join(destinationpath, relative_path) if not os.path.isdir(dist_path): os.makedirs(dist_path) last_copy_folder = "" for fn0 in files: fn = os.path.join(root, fn0) fn2 = os.path.join(dist_path, fn0) _ = False if not os.path.isfile(fn2): is_copy = True else: statinfo = os.stat(fn) statinfo2 = os.stat(fn2) is_copy = ( round(statinfo.st_mtime, 3) != round(statinfo2.st_mtime, 3) or statinfo.st_size != statinfo2.st_size ) if is_copy: if dist_path != last_copy_folder: print("[%s]" % dist_path) print("copying '%s' ..." % fn0) shutil.copy2(fn, fn2) sync_file_count += 1 sync_file_size += os.stat(fn).st_size if sync_file_count > 0: print("-" * 50) print("%d files synchronized!" % sync_file_count) if sync_file_size > 0: print("%d bytes." % sync_file_size) print("done!") def main(): global destinationpath global sourcepath destinationpath = "D:/dest" sourcepath = "D:/src" sync(sourcepath, destinationpath) event_handler = CreatedHandler() observer = Observer() observer.schedule(event_handler, path=sourcepath, recursive=True) observer.start() try: while 1: destinationpath = sourcepath time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == '__main__': main()
clear