【问题标题】:How do I check for a file to be finished downloading Python3?如何检查要完成下载 Python3 的文件?
【发布时间】:2018-08-29 06:32:25
【问题描述】:

我正在尝试弄清楚如何检查下载是否已完成。基本上我希望它等到文件完成下载然后打印:下载完成。

这是我当前的代码以及我想用它做什么:

from  urllib import request

print("Are you sure you want to download the newest file? y/n")
answer = input()

while True:
    if answer == 'y':
        print("Downloading file...")
        downloading = True
        request.urlretrieve("FILE_URL", "FILE_NAME")
    elif answer == 'n':
         exit()
    else:
         print("That is not a valid answer, please answer with y/n.")
         answer = input()

#I need some sort of function here that checks if the file is still being 
#downloaded

when downloading == False:
    print("Download Completed.")

【问题讨论】:

  • while answer is not 'y' or 'n': 不会像您认为的那样做。见How to test multiple variables against a value?。我会编辑它,因为它与问题无关。
  • 它可以工作。
  • 巧合的是,是的。实际上,我刚刚破解了你的密码……等等……我们走了。
  • @VineethSai 文件存在并不意味着下载完成。
  • 这就是整个问题。下载大文件时,我需要知道它何时完成。我早些时候发布了一个问题,说我的代码不起作用,但实际上下载还没有完成,我浪费了大家的时间。我需要知道何时可以安全地关闭程序并打开文件。

标签: python python-3.x


【解决方案1】:

如果您使用urllib.request.urlretrieve reporthook 选项,您可以监控下载进度,尤其适用于大文件,如下所示:

import urllib.request

def Download_Progress(block_num, block_size, total_size):
    downloaded = block_num * block_size
    progress = int((downloaded/total_size)*100)
    print ("Download Progress",str(progress),"%")

url = "https://somesite/some.pdf"
urllib.request.urlretrieve(url, 'mycopy.pdf', reporthook=Download_Progress)
print ("Finished")

您也可以使用requests 包实现类似的功能。

import requests
url = "https://somesite/some.pdf"

#Get the headers of the remote file
h = requests.head(url, allow_redirects=True)

#Get the size of the file
total_size = int(h.headers.get('content-length'))

#Request the file download with stream set to True
r = requests.get(url, stream=True)

#Open a local file for writing
localfile = open("mycopy.pdf", "wb")
chunks = 0

#Process the file as it arrives
for chunk in r.iter_content(chunk_size=512):
    if chunk:
        chunks += 1
        downloaded = chunks * 512
        # An approximation as the chunks don't have to be 512 bytes
        progress = int((downloaded/total_size)*100)
        print ("Download Progress",str(progress),"%")
        localfile.write(chunk)
print("Finished")

【讨论】:

    【解决方案2】:

    当urlretrieve返回时,文件已经下载完毕。

    参见docs中的用法示例:

    >>> import urllib.request
    >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
    >>> html = open(local_filename)
    

    可以看出,文件在调用urlretrieve 后立即打开,因为它已经创建并且内容已经写入那里。

    【讨论】:

    • 那么我该如何在我的代码中实现它呢?我需要一些可以将“正在下载 == 真”更改为“正在下载 == 假”的东西
    • @NeverEndingCycle 关键是你不需要这些。 下载已经完成。在urlretrieve(...)调用之后添加print("Download Completed.")就完成了。
    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 2015-09-28
    • 1970-01-01
    • 2010-12-06
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多