import urllib
from urllib.request import urlretrieve
#解决urlretrieve下载文件不完全的问题且避免下载时长过长陷入死循环
def auto_down(url,filename):
    try:
        urlretrieve(url,filename,jindu)
    except socket.timeout:
        count = 1
        while count <= 15:
            try:
                urlretrieve(url, filename,jindu)
                break
            except socket.timeout:
                err_info = 'Reloading for %d time' % count if count == 1 else 'Reloading for %d times' % count
                print(err_info)
                count += 1
        if count > 15:
            print("下载失败")

#urlretrieve()的回调函数,显示当前的下载进度
#a为已经下载的数据块
#b为数据块大小
#c为远程文件的大小
global myper
def jindu(a,b,c):
    if not a:
        print("连接打开")
    if c<0:
        print("要下载的文件大小为0")
    else:
        global myper
        per=100*a*b/c

        if per>100:
           per=100
        myper=per
        print("当前下载进度为:" + '%.2f%%' % per)
    if per==100:
            return True