Python3用sys和time模块实现进度条
import sys import time def view_bar(num, total): rate = float(num) / float(total) rate_num = int(rate * 100) r = '\r[%s%s]%d%%' % ("="*num, " "*(100-num), rate_num, ) sys.stdout.write(r) sys.stdout.flush() if __name__ == '__main__': for i in range(0, 101): time.sleep(0.1) view_bar(i, 100)
另一种函数模式:
会根据num的变化,实时输出进度条的进度,从而实现了类似上传下载中的进度条模式。
def view_bar(num, mes): """ 进度条方法 :param num: 百分比数字 :param mes: 输出信息 :return: """ rate_num = num number = int(rate_num / 4) hashes = '=' * number spaces = ' ' * (25 - number) r = "\r\033[31;0m%s\033[0m:[%s%s]\033[32;0m%d%%\033[0m" % (mes, hashes, spaces, rate_num,) sys.stdout.write(r) sys.stdout.flush()