在Python中實(shí)現(xiàn)進(jìn)度條可以使用print
函數(shù)結(jié)合sys.stdout.write
和sys.stdout.flush
來實(shí)現(xiàn)。以下是一個(gè)簡單的示例代碼:
import sys
import time
def progress_bar(total, progress):
bar_length = 50
progress = float(progress) / float(total)
arrow = '=' * int(round(progress * bar_length))
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write('\rProgress: [{0}] {1}%'.format(arrow + spaces, int(progress * 100)))
sys.stdout.flush()
total = 100
for i in range(total):
progress_bar(total, i+1)
time.sleep(0.1)
print("\nProcess completed!")
在上面的代碼中,progress_bar
函數(shù)接受兩個(gè)參數(shù)total
和progress
,分別表示總的進(jìn)度和當(dāng)前的進(jìn)度。然后根據(jù)當(dāng)前進(jìn)度計(jì)算進(jìn)度條的長度,并使用sys.stdout.write
輸出進(jìn)度條。最后使用sys.stdout.flush
刷新輸出,實(shí)現(xiàn)動(dòng)態(tài)更新進(jìn)度條。