很难解释为标题。 我正在这里下载文件并使用进度条的修改版本:https://gist.github.com/somada141/b3c21f7462b7f237e522
我只想显示诸如10%--- 20%---等增量,但是代码已调整为显示小数位,这意味着默认输出将为10.12%10.45%10.67%10.89%。
因此,即使我执行if语句并与10匹配,由于上述所有匹配都等于10,我最终还是要进行10%的打印4次。
完整代码
response = urllib2.urlopen(url)
with open("myfile.zip", "wb") as local_file:
local_file.write(self.chunk_read(response, report_hook=self.chunk_report))
def chunk_report(self, bytes_so_far, chunk_size, total_size):
percent = round(float(bytes_so_far) / total_size * 100))
if percent == 10:
print("%0.0f%%\r" % (percent))
elif percent == 20:
print("%0.0f%%\r" % (percent))
elif percent == 30:
print("%0.0f%%\r" % (percent))
if bytes_so_far >= total_size:
sys.stdout.write('\n')
def chunk_read(self, response, chunk_size=8192, report_hook=None):
total_size = response.info().getheader('Content-Length').strip()
total_size = int(total_size)
bytes_so_far = 0
data = []
while 1:
chunk = response.read(chunk_size)
bytes_so_far += len(chunk)
if not chunk:
break
data += chunk
if report_hook:
report_hook(bytes_so_far, chunk_size, total_size)
return "".join(data)
这给出了输出:
10%
10%
10%
10%
20%
20%
20%
20%
我希望只打印10%,一次只打印20%。
编辑: 根据joaquin的回答,完全有效的代码如下:
response = urllib2.urlopen(url)
with open("myfile.zip", "wb") as local_file:
local_file.write(self.chunk_read(response, report_hook=self.chunk_report))
def chunk_report(self, bytes_so_far, chunk_size, total_size, status):
percent = float(bytes_so_far) / total_size
percent = round(percent*100)
if percent >= status:
print("%0.0f%%\r" % (percent))
status += 10
return status
if bytes_so_far >= total_size:
print('\n')
def chunk_read(self, response, chunk_size=8192, report_hook=None):
total_size = response.info().getheader('Content-Length').strip()
total_size = int(total_size)
bytes_so_far = 0
data = []
status = 0
while 1:
chunk = response.read(chunk_size)
bytes_so_far += len(chunk)
if not chunk:
break
data += chunk
if report_hook:
status = report_hook(bytes_so_far, chunk_size, total_size, status)
return "".join(data)
答案 0 :(得分:1)
这里有一个示例,该示例可以产生10%.... 100%的内容,而无需使用if
系列
target_percent = 10
total_size = 1000
for bytes_so_far in range(1, 1000):
percent = float(bytes_so_far) / total_size
percent = round(percent*100)
if percent >= target_percent:
print("%0.0f%%\r" % (percent))
target_percent += 10
您得到:
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
这可以在函数内部进行组织:
def get_percent(bytes_so_far, total_size, status):
percent = float(bytes_so_far) / total_size
percent = round(percent*100)
if percent >= status:
print("%0.0f%%\r" % (percent))
status += 10
return status
如果我们模拟对该函数的重复调用:
size = 1000
status = 10
for bytes_so_far in range(1, 1000):
status = get_percent(bytes_so_far, size, status)
我们再次得到:
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%