我最近碰到这个问题。我一次下载了多个文件,如果下载失败,我必须以超时的方式构建。
代码每秒钟检查一次下载目录中的文件名,完成后退出,或者完成时间超过20秒。返回的下载时间用于检查下载是否成功或是否超时。import time
import os
def download_wait(path_to_downloads):
seconds = 0
dl_wait = True
while dl_wait and seconds < 20:
time.sleep(1)
dl_wait = False
for fname in os.listdir(path_to_downloads):
if fname.endswith('.crdownload'):
dl_wait = True
seconds += 1
return seconds
我相信这只适用于chrome文件,因为它们以.crdownload扩展名结尾。可能有一种类似的方法签入其他浏览器。
编辑:我最近更改了使用此函数的方式,因为.crdownload没有显示为扩展名。实际上,这也只是等待正确数量的文件。def download_wait(directory, timeout, nfiles=None):
"""
Wait for downloads to finish with a specified timeout.
Args
----
directory : str
The path to the folder where the files will be downloaded.
timeout : int
How many seconds to wait until timing out.
nfiles : int, defaults to None
If provided, also wait for the expected number of files.
"""
seconds = 0
dl_wait = True
while dl_wait and seconds < timeout:
time.sleep(1)
dl_wait = False
files = os.listdir(directory)
if nfiles and len(files) != nfiles:
dl_wait = True
for fname in files:
if fname.endswith('.crdownload'):
dl_wait = True
seconds += 1
return seconds