看门狗 Python - 未观察到从 Chrome 完全下载的文件

问题描述

我的程序中有一段代码,它基本上检查文件是否已创建和重命名,以便它可以将文件移动到另一个目录。

class Handler(FileSystemEventHandler):
    @staticmethod
    def on_moved(event):
        if event.is_directory:
            return None
        time.sleep(5)
        move_file(event.dest_path,DESTINATION_FOLDER)

它总是在 chrome 下载时出错:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\something\\Downloads\\Unconfirmed 116567.crdownload'

有什么方法可以让 Watchdog 检查 COMPLETED 下载而不是 Chrome 在开始下载时创建的 .crdownload 文件

提前致谢!

解决方法

您可以尝试使用 on_modified 事件。并且还忽略 .crdownload 文件。这样,您就可以跟踪最终重命名的文件(下载完成后)。

def wait_till_file_is_created(self,source_path):
    historicalSize = -1
    while (historicalSize != os.path.getsize(source_path)):
        historicalSize = os.path.getsize(source_path)
        time.sleep(1)

def on_modified(self,event):
    print('\nEvent type: modified; Source file: ',event.src_path)
    if '.crdownload' not in event.src_path:
        # wait for the file copy to be completed (add sleep or check size repeatedly with a delay)
        self.wait_till_file_is_created(event.src_path)
        # code to move file to the required path