Python 2 & Python 3打印程序执行进度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dugudaibo/article/details/84445527

  在跑耗费时间比较长的程序时我们往往需要估计下还需要多长时间,这个时候如果知道了已经完成了多少,就可以很好地帮助我们估计时间。

  这段代码是基于 python 3 编写的,像使用 python 2 的同学可以在程序的最上面添加这句话

# -*- coding=utf-8 -*-
from __future__ import print_function

  函数的具体代码如下

def progress(percent,width=50):
	'''进度打印功能
	   每次的输入是已经完成总任务的百分之多少

	'''
	if percent >= 100:
		percent=100
  
	show_str=('[%%-%ds]' %width) %(int(width * percent/100)*"#") #字符串拼接的嵌套使用
	print('\r%s %d%%' %(show_str,percent),end='')

其中可以看到函数的输入是已经执行的百分比,下面将介绍一个使用这个方法的完整例子

# -*- coding=utf-8 -*-
from __future__ import print_function

def progress(percent,width=50):
	'''进度打印功能
	   每次的输入是已经完成总任务的百分之多少

	'''
	if percent >= 100:
		percent=100
  
	show_str=('[%%-%ds]' %width) %(int(width * percent/100)*"#") #字符串拼接的嵌套使用
	print('\r%s %d%%' %(show_str,percent),end='')

total = 100
count = 0
for i in range(total):
	a = i*2
	count += 1
	progress(100*count/total)
print ('\nfinished!')

  执行上面的代码会得到如下的输出

[##################################################] 100%
finished!

其中有几点需要注意,首先是函数的输入,因为要输入的是百分比,所以要乘以 100 ,即 progress(100*count/total);另外在执行 progress 的过程中最好不要再有其他的 print 操作,因为这样的话就没有办法保证输出的一个进度条,会得到很多行的进度条(你额外调用了 print 多少次,就会有多少行进度条);最后如果你想在执行完 print 操作后再 print 其他的东西,最好在需要打印的前面加上 \n,否则会直接在进度条后面打印出来。

猜你喜欢

转载自blog.csdn.net/dugudaibo/article/details/84445527