例4.1.设置一组文本进度条,使之运行效果如下:
--------执行开始--------
% 0 [->**********]
%10 [*->*********]
%20 [**->********]
%30 [***->*******]
%40 [****->******]
%50 [*****->*****]
%60 [******->****]
%70 [*******->***]
%80 [********->**]
%90 [*********->*]
%100[**********->]
--------执行结束--------
1 #文本进度条1.py
2 importtime3 print("{0:-^20}".format('执行开始'))4 scale = 10
5 for i in range(scale+1):6 a = '*' *i7 b = '*' * (scale -i)8 c = (i/scale)*100
9 print("%{:^3.0f}[{}->{}]".format(c,a,b))10 time.sleep(0.5)11 print("{0:-^20}".format('执行结束'))
在此讲解time库的使用:
获取时间:time() 得到时间戳;
ctime()得到时间的字符串表达形式;
gmtime()得到时间的程序表达形式。
时间格式化:strftime(tpl ,ts ) 其中tpl是格式化模板字符串,ts是计算机内部时间类型变量
如>>>t = time.gmtime()
time.strftime("%Y-%m-%d %H:%M:%S",t)
strptime(str,tpl)
程序计时:perf_counter() 返回精确的时间计数值。
sleep(s)休眠时间,s为秒
例4.2在命令提示符窗口实现单行动态刷新,进度条运行效果如下
100%>>>
>>> importtime>>> for i in range(101):
...print("\r{:2}%".format(i),end="")
... time.sleep(0.05)
...
例4.3实现带刷新的文本进度条
1 #TextProBarV3.py
2 importtime3 scale = 50
4 print("执行开始".center(scale//2,"-"))5 start =time.perf_counter()6 for i in range(scale + 1):7 a = "*" *i8 b = '.' * (scale -i)9 c = (i/scale)*100
10 dur = time.perf_counter() -start11 print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="")12 time.sleep(0.1)13 print("\n"+"执行结束".center(scale//2,"-"))
-----------执行开始----------
100%[**************************************************->]5.03s
-----------执行结束----------
博客参考《Python程序设计基础》高等教育出版社(第2版) 嵩天,礼欣,黄天羽著
推荐与上述教材配套的北京理工大学 嵩天,礼欣,黄天羽老师的MOOC