很难解释为标题。 我正在下载一个文件,并在这里使用进度条的修改版本:https://gist.github.com/somada141/b3c21f7462b7f237e522
我只想显示增量,如10%--20%--等,但是代码被调整为显示小数位,这意味着默认输出将是10.12%10.45%10.67%10.89%。你知道吗
因此,即使我做了一个if语句并与10匹配,我最终得到的结果是10%打印4倍于以上所有匹配到10的结果。你知道吗
完整代码
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)
这里有一个例子,它产生10%…100%,而不需要
if
系列你会得到:
这可以组织在一个函数中:
如果我们模拟对该函数的重复调用:
我们再次得到:
相关问题 更多 >
编程相关推荐