用progressbar运行urllib2会调用程序崩溃

2024-10-02 08:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,所以我的代码有问题(可能不是urllib2本身),但它不会创建进度条并崩溃。但在等待代码完成后下载我的文件。有没有我可以阻止挂起,并可能分解成更小的块下载,因为我没有什么经验与python。。。我的代码如下:

def iPod1():
pb = ttk.Progressbar(orient ="horizontal",length = 200, mode ="indeterminate")
pb.pack(side="top") 
pb.start()
download = "http://downloads.sourceforge.net/project/whited00r/7.1/Whited00r71-iPodTouch1G.zip?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fwhited00r%2Ffiles%2F7.1%2F&ts=1405674672&use_mirror=softlayer-ams"
request = urllib2.urlopen( download)
pb.start()
output = open("Whited00r71-iPodTouch1G.zip", "wb")
output.write(request.read())
output.close()
pb.stop
tkMessageBox.showinfo(title="Done", message="Download complete. Please follow the installation instructions provided in the .html file.")   

Tags: 文件the代码进度条outputrequestdownload经验
1条回答
网友
1楼 · 发布于 2024-10-02 08:25:01

通过将下载移动到自己的线程中,可以避免挂起/冻结GUI。由于GUI不能从运行Tk mainloop的线程以外的其他线程更改,因此我们必须定期检查下载线程是否已完成。这通常是通过在小部件对象上使用after()方法重复调度延迟的函数调用来实现的。你知道吗

在将整个文件写入本地文件之前不将其读入内存可以通过shutil.copyfileobj()完成。你知道吗

import shutil
import tkMessageBox
import ttk
import urllib2
from threading import Thread

IPOD_1_URL = (
    'http://downloads.sourceforge.net/project/whited00r/7.1/'
    'Whited00r71-iPodTouch1G.zip'
    '?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fwhited00r%2Ffiles%2F7.1%2F'
    '&ts=1405674672'
    '&use_mirror=softlayer-ams'
)


def download(url, filename):
    response = urllib2.urlopen(url)
    with open(filename, 'wb') as output_file:
        shutil.copyfileobj(response, output_file)


def check_download(thread, progress_bar):
    if thread.is_alive():
        progress_bar.after(500, check_download, thread, progress_bar)
    else:
        progress_bar.stop()
        tkMessageBox.showinfo(
            title='Done',
            message='Download complete. Please follow the installation'
                ' instructions provided in the .html file.'
        )


def start_download_for_ipod1():
    progress_bar = ttk.Progressbar(
        orient='horizontal', length=200, mode='indeterminate'
    )
    progress_bar.pack(side='top')
    progress_bar.start()
    thread = Thread(
        target=download, args=(IPOD_1_URL, 'Whited00r71-iPodTouch1G.zip')
    )
    thread.daemon = True
    thread.start()
    check_download(thread, progress_bar)

相关问题 更多 >

    热门问题