關鍵點是輸出'\r'這個字符可以使光標回到一行的開頭,這時輸出其它內容就會將原內容覆蓋。
import time import sys def progress_test(): bar_length=20 for percent in xrange(0, 100): hashes = '#' * int(percent/100.0 * bar_length) spaces = ' ' * (bar_length - len(hashes)) sys.stdout.write("\rPercent: [%s] %d%%"%(hashes + spaces, percent)) sys.stdout.flush() time.sleep(1) progress_test()