首页 > 代码库 > Python 进度条

Python 进度条

经常要用到sleep时间,

开始一直用sleepxxx来显示

后面觉得这样还是不够直观。

效果如下:

 ==================================SLEEP 60 s===================================

 ETA: 00:00 [ ================================================================ ]

 

def sleep_time(duration, width=80):
    msg = "SLEEP %s s"%(duration)
    left = (width-len(msg))//2
    print("\r\n %s%s%s\r\n"%(mk_hr("=",left-1),msg,mk_hr("=",width-left-len(msg)))) 
    cnt = 0
    while (cnt < duration + 1):
        sys.stdout.write("\r%s\r" % (progress_bar(duration, cnt, width)))
        sys.stdout.flush()
        time.sleep(1)
        cnt += 1
    print("\r\n")

def progress_bar(total, cnt, width=80):

    def progress_print(total, width, cnt):
        left = cnt * width//total
        cent = "=" if cnt % 2 == 0 else " "
        if cnt == total:
            cent = ""
        return mk_hr("=", left) + cent + mk_hr("-", width-left-1)

    msg = " ETA: "
    ucnt = total-cnt
    if total < 3600:
        msg = "%s%s"%(msg,"%02d:%02d"%(ucnt//60,ucnt%60))
    else:
        msg = "%s%s"%(msg,"%02d:%02d:%02d"%(ucnt//3600,(ucnt-(ucnt//3600)*3600)//60,ucnt%60))
    left = len(msg)
    if left > width-1:
        return msg
    else:
        return "%s [ %s ]" % (msg, progress_print(total, width-left-5, cnt))
def mk_hr(fill, width): result = "" for i in xrange(int(width)): result += fill return result

 

Python 进度条