python3错误:reporth中的浮点除零

2024-04-29 15:35:16 发布

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

我正在尝试编写一个简单的代码,从.json文件下载4365个文件(.mp4、.wmv、.jpeg&;pdf),下载部分已经完成,但是我想得到一个reporthook,告诉我,%,Mb,速度和持续时间。你知道吗

即使有时它运行,我也会出错:

file "dw.py", line 21, in reporthook
    speed = int(progress_size / (1024 *  duration))
ZeroDivisionError: float division by zero

这是我的密码:

import urllib.request
import json
import sys
import time

with open('finalsinbin.json') as json_data:   # importar toda la lista de videos 
items = json.load(json_data)

def reporthook(count, block_size, total_size):
    global start_time
    if count == 0:
        start_time = time.time()
        return
    duration = time.time() - start_time
    progress_size = int(count * block_size)
    speed = int(progress_size / (1024 * duration))
    percent = min(int(count*blockSize*100/totalSize),100)
    sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration))
    sys.stdout.flush()


def batch(startAt, stopAt): 
   a=0 
   for i in items:
        a+=1

    if a < startAt or a > stopAt:
        continue

    num = i['id']
    url = i['url']
    typ = i['type']
    urlfinal = (url + "/" + str(num) + typ)
    filename = (str(num) + typ)
    print( '[%d] Descargando el archivo %s...' % (a, str(num) + typ))
    urllib.request.urlretrieve(urlfinal, filename, reporthook)  

batch(1, 100) #download file from n to N

Tags: importjsonurlsizetimecountsysstart
1条回答
网友
1楼 · 发布于 2024-04-29 15:35:16

试着用time.perf_counter()代替time.time()。至少在我的环境中,time.perf_counter()从未变为0,如下所示。你知道吗

import time

def time_perf_counter():
    start_time = time.perf_counter()
    return time.perf_counter() - start_time

def time_time():
    start_time = time.time()
    return time.time() - start_time

def test_timer(timer, n):
    count = 0
    for i in range(n):
        if timer() == 0:
            count += 1
    return count

n_test = 100000

print('{:>6s} / {:>6s}'.format(
    '# fail',
    '# test'))
print('{:6d} / {:6d}'.format(
    test_timer(time_perf_counter, n_test),
    n_test))
print('{:6d} / {:6d}'.format(
    test_timer(time_time, n_test),
    n_test))

例如,结果如下:

# fail / # test
     0 / 100000
 89109 / 100000

我的环境:MBP High Sierra,Python 3.6.3

相关问题 更多 >