mengchaosb 2021-01-21 16:29 采纳率: 0%
浏览 13

pthon小白请教,我的代码运行中同步文件过程中,wathdog功能没起作用呢?

# -*- 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()
  • 写回答

1条回答 默认 最新

  • mengchaosb 2021-01-25 15:36
    关注

    clear

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看