繁体   English   中英

Python 3:如何创建用于下载文件的文本进度栏?

[英]Python 3: How to create a text progress bar for downloading files?

我目前有这个:

def download_dropbox(url, pre_file_name):
    file = url[42:]
    file = file[:-5]
    file_name = pre_file_name + file
    print('Downloading from ' + url + ' to ' + file_name)
    print(file)
    u = urllib.request.urlopen(url)
    data = u.read()
    u.close()

    with open(file_name, "wb") as f:
        f.write(data)
    print('Download Completed from ' + url + ' and saved to ' + file_name)

这基本上是从保管箱下载文件并将其保存到目录中。 但是我希望能够有某种文本进度条,例如:


[====] 50%


要么


50%

我认为最难的部分是使用任何外部模块(如加载栏模块等)来完成它。此外,正如标题所述,我需要在python 3中使用它。谢谢。

编辑:

感谢Martin Evans在while循环和进度栏中读取数据,这是代码的最终结果:

#Get the total number of bytes of the file to download before downloading
print ("opening url:", url)
u = urllib.request.urlopen(url)
meta = u.info()
print(str(meta).split())
metaInfo = str(meta).split()
print(len(metaInfo))
print ("Content-Length:" + metaInfo[46] + " bytes")
fileTotalbytes=int(metaInfo[46])

data_blocks = []
# total = int(metaInfo[46])
total=0

while True:
    block = u.read(1024)
    data_blocks.append(block)
    total += len(block)
    hash = ((60*total)//fileTotalbytes)
    print("[{}{}] {}%".format('#' * hash, ' ' * (60-hash), int(total/fileTotalbytes*100)), end="\r")

    if not len(block):
        break

data=b''.join(data_blocks) #had to add b because I was joining bytes not strings
u.close()

with open('test.zip', "wb") as f:
        f.write(data)

您可以在开头使用\\r打印到行首并覆盖前一个文本(因此,如果要清除字符,则需要写空格)。 这是一个简单的例子:

from time import sleep
x = 0
while x < 20:
    print('\r' + '.' * x, end="")
    x += 1
    sleep(0.1)

要回答您的主要问题(如何制作文本进度条),可以使用类似以下内容的方法:

import time

for n in range(1,101):
    hash = ((60*n)//100)
    print("[{}{}] {}%".format('#' * hash, ' ' * (60-hash), n), end="\r")
    time.sleep(0.05)

这将为您提供以下内容:

[###########################                                 ] 45%

但是,您的主要问题是,除非您已经事先知道要下载的项目的确切大小,否则没有明显的方法来确定最终将下载多少字节。 如果您控制服务器端,则可以安排在开始之前获取长度。

不过,您至少可以将read()行至少转换为以下内容:

u = urllib.request.urlopen(url)

data_blocks = []
total = 0

while True:
    block = fd.read(1024)
    data_blocks.append(block)
    total += len(block)
    print("Downloaded {} bytes".format(total), end="\r")

    if not len(block):
        break

data = "".join(data_blocks)
u.close()

通过这种方式,您可以一次阅读一点,然后可以提供反馈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM