【python實例教學】
【每天一例,九周學會python】
實例3-2:文本進度條
描述
採用字符串方式打印可以動態變化的文本進度條,進度條需要能在一行中逐漸變化。
要求如下:
(1) 採用sleep()模擬一個持續的進度,獲得文本進度條的變化時間;
(2) 通過print()函數實現單行動態刷新,在print()函數中更換參數end的默認值為'',每次使用print()函數輸出時不能換行;
(3) 要能回退:打印後光標到之前的位置 \\r。
請在Windows的命令行(cmd或PowerShell)或其他操作系統的命令行下執行Python程序,獲得進度條效果。
參考代碼:
# TextproBarv3.py
import time
scale = 50
print("執行開始".center(scale//2,"-"))
start = time.perf_counter()
for i in range(scale+1):
a = "*" * i
b = "." * (scale - i)
c = (i/scale)*100
dur = time.perf_counter()-start
print("\\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="")
time.sleep(0.1)
print("\\n"+"執行結束".center(scale//2,"-"))
注意:些程序不能在IDLE下運行。
閱讀更多 愛python 的文章
關鍵字: Python 文本 PowerShell