在学习Python语言程序设计基础中3.7.3的带刷新的文本进度条时,发现time.clock的方法无法使用。提示:AttributeError: module ‘time’ has no attribute ‘clock’。经过查询发现time.clock()在Python3.8中已经废除。
import time scale=50 print("执行开始".center(scale//2,'-')) t=time.clock() for i in range(scale+1): a='*'*i b='.'*(scale-i) c=(i/scale)*100 t-=time.clock() print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\ end='') time.sleep(0.05) print("\n"+"执行结束".center(scale//2,'-'))经过查找发现有两种方法
这两种方法的区别在于是否计算time.sleep()中的时间
import time t0=time.process_time() time.sleep(1) t1=time.process_time() print(t1-t0)#=0.0 t2=time.perf_counter() time.sleep(1) t3=time.perf_counter() print(t3-t2)#=1.0002965000000001经过测试,方法一perf_counter()计算sleep()的值,方法二process_time()不计算。
结合该题,题中使用了sleep()方法,所以我们采用方法一。
import time scale=50 print("执行开始".center(scale//2,'-')) t=time.perf_counter() for i in range(scale+1): a='*'*i b='.'*(scale-i) c=(i/scale)*100 t-=time.perf_counter() print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\ end='') time.sleep(0.05) print("\n"+"执行结束".center(scale//2,'-'))结果如下 同书上一致,问题解决。 如想进一步了解这两种方法可参考[https://blog.csdn.net/qq_27283619/article/details/89280974] 给个三连吧