Python - 检查下载是否完成

问题描述 投票:0回答:1

我正在使用看门狗来监控我的下载并将它们移动到其他地方。但是,当下载量很大并且在下载完成之前调用

shutil.move
时,目标文件不完整或为空并且不会删除源文件。如您所见,我试过简单地等待,但对于大量下载,我无法知道我需要等待多长时间,而且计时器通常过早到期。

class DownloadHandler(FileSystemEventHandler):
    
    def on_created(self, event):
        if event.src_path.endswith(".zip"):
            thread.start_new_thread(move_file, (event.src_path, dst))


def move_file(src, dst):
    time.sleep(1)
    shutil.move(src, dst)

我也尝试过实施this answer,但对于大量下载它仍然失败(可能是因为操作系统没有足够频繁地更新文件大小/直到下载完成)。有没有可靠的方法来检查 Python 下载是否完成?

python python-3.x download python-multithreading python-watchdog
1个回答
0
投票

展开评论,我的意思不是简单的等待,而是主动检查大小变化,即

def move_file(src, dst):
    last_size = Path(src).stat().st_size
    time.sleep(1)
    while (current_size := Path(src).stat().st_size) != last_size:
        time.sleep(1)
        last_size = current_size
    shutil.move(src, dst)

或者,您可以尝试检查用于下载的程序是否仍然打开了文件(请参阅https://superuser.com/questions/97844/how-can-i-determine-what-process-有一个文件在 linux 中打开)。

© www.soinside.com 2019 - 2024. All rights reserved.