python的print函數(shù)如何實(shí)現(xiàn)進(jìn)度條

小樊
115
2024-07-14 15:19:21
欄目: 編程語言

在Python中實(shí)現(xiàn)進(jìn)度條可以使用print函數(shù)結(jié)合sys.stdout.writesys.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ù)totalprogress,分別表示總的進(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)度條。

0