python3 进度条
首先看下sys模块里的标准输出stdout
import sys sys.stdout.write("111") sys.stdout.write("222")
执行结果:
111222
看下带有回车\r的情况
import sys sys.stdout.write("111") sys.stdout.write("\r222")
执行结果:
222
看怎么制作进度条
import sys import time total = 100 for i in range(1, total+1): percentage = int(100/total*i) # print(f"\r{percentage}%", ">" * percentage, end="") sys.stdout.write(f"\r{percentage}%" + ">"*percentage) # 同上 sys.stdout.flush() time.sleep(0.1)
执行效果:
100%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\r 默认表示将输出的内容返回到第一个指针,这样的话,后面的内容会覆盖前面的内容。
# coding:utf-8 import sys import time def process_bar(total, now): process = int(now * 100 / total) sys.stdout.write(f"\r[ {process}% ]" + ">" * process) sys.stdout.flush() time.sleep(0.1) for i in range(1, 100 + 1): process_bar(100, i)
执行结果:
[ 100% ]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>