首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >下载Python 3的进度条

下载Python 3的进度条
EN

Stack Overflow用户
提问于 2012-12-14 23:00:17
回答 2查看 12.7K关注 0票数 12

我需要在Python 3的文件下载过程中显示一个进度。我在Stackoverflow上看过一些主题,但考虑到我是编程新手,没有人发布完整的示例,只是其中的一小部分,或者我可以在Python 3上工作的示例,没有一个对我有好处……

其他信息:

好的,我有这个:

代码语言:javascript
复制
from urllib.request import urlopen
import configparser
#checks for files which need to be downloaded
print('    Downloading...')
file = urlopen(file_url)
#progress bar here
output = open('downloaded_file.py','wb')
output.write(file.read())
output.close()
os.system('downloaded_file.py')

脚本通过python命令行运行

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-16 04:06:50

有一个urlretrieve()可以将url下载到一个文件中,并允许指定一个reporthook回调来报告进度:

代码语言:javascript
复制
#!/usr/bin/env python3
import sys
from urllib.request import urlretrieve

def reporthook(blocknum, blocksize, totalsize):
    readsofar = blocknum * blocksize
    if totalsize > 0:
        percent = readsofar * 1e2 / totalsize
        s = "\r%5.1f%% %*d / %d" % (
            percent, len(str(totalsize)), readsofar, totalsize)
        sys.stderr.write(s)
        if readsofar >= totalsize: # near the end
            sys.stderr.write("\n")
    else: # total size is unknown
        sys.stderr.write("read %d\n" % (readsofar,))

urlretrieve(url, 'downloaded_file.py', reporthook)

这是一个GUI进度条:

代码语言:javascript
复制
import sys
from threading import Event, Thread
from tkinter import Tk, ttk
from urllib.request import urlretrieve

def download(url, filename):
    root = progressbar = quit_id = None
    ready = Event()
    def reporthook(blocknum, blocksize, totalsize):
        nonlocal quit_id
        if blocknum == 0: # started downloading
            def guiloop():
                nonlocal root, progressbar
                root = Tk()
                root.withdraw() # hide
                progressbar = ttk.Progressbar(root, length=400)
                progressbar.grid()
                # show progress bar if the download takes more than .5 seconds
                root.after(500, root.deiconify)
                ready.set() # gui is ready
                root.mainloop()
            Thread(target=guiloop).start()
        ready.wait(1) # wait until gui is ready
        percent = blocknum * blocksize * 1e2 / totalsize # assume totalsize > 0
        if quit_id is None:
            root.title('%%%.0f %s' % (percent, filename,))
            progressbar['value'] = percent # report progress
            if percent >= 100:  # finishing download
                quit_id = root.after(0, root.destroy) # close GUI

    return urlretrieve(url, filename, reporthook)

download(url, 'downloaded_file.py')

在Python3.3上,urlretrieve()有不同的reporthook接口(see issue 16409)。要解决此问题,您可以通过FancyURLopener访问上一个界面

代码语言:javascript
复制
from urllib.request import FancyURLopener
urlretrieve = FancyURLopener().retrieve

要更新同一线程中的进度条,可以内联urlretrieve()代码:

代码语言:javascript
复制
from tkinter import Tk, ttk
from urllib.request import urlopen

def download2(url, filename):
    response = urlopen(url)
    totalsize = int(response.headers['Content-Length']) # assume correct header
    outputfile = open(filename, 'wb')

    def download_chunk(readsofar=0, chunksize=1 << 13):
        # report progress
        percent = readsofar * 1e2 / totalsize # assume totalsize > 0
        root.title('%%%.0f %s' % (percent, filename,))
        progressbar['value'] = percent

        # download chunk
        data = response.read(chunksize)
        if not data: # finished downloading
            outputfile.close()
            root.destroy() # close GUI
        else:
            outputfile.write(data) # save to filename
            # schedule to download the next chunk
            root.after(0, download_chunk, readsofar + len(data), chunksize)

    # setup GUI to show progress
    root = Tk()
    root.withdraw() # hide
    progressbar = ttk.Progressbar(root, length=400)
    progressbar.grid()
    # show progress bar if the download takes more than .5 seconds
    root.after(500, root.deiconify)
    root.after(0, download_chunk)
    root.mainloop()

download2(url, 'downloaded_file.py')
票数 25
EN

Stack Overflow用户

发布于 2012-12-15 21:55:23

我认为这段代码可以帮助你。我不太确定这是不是你想要的。至少它应该给你一些东西来工作。

代码语言:javascript
复制
import tkinter 
from tkinter import ttk
from urllib.request import urlopen


def download(event):
    file = urlopen('http://www.python.org/')
    output = open('downloaded_file.txt', 'wb')
    lines= file.readlines()
    i = len(lines)

    for line in lines:
        output.write(line)
        pbar.step(100/i)

    output.close()
    file.close()




root = tkinter.Tk()
root.title('Download bar')

pbar = ttk.Progressbar(root, length=300)
pbar.pack(padx=5, pady=5)

btn = tkinter.Button(root, text="Download")
# bind to left mouse button click
btn.bind("<Button-1>", download)
btn.pack(pady=10)

root.mainloop()

这很管用,我已经试过了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13881092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档