1. 程式人生 > 其它 >命令列進度條的python實現

命令列進度條的python實現

技術標籤:電腦科學與技術pythonprocessing進度條命令列進度條列印命令列覆蓋輸出

進度條

執行環境

  • Python 3.7.3
  • conda 4.9.2
  • anaconda Command line client (version 1.7.2)

等待效果

效果截圖
在這裡插入圖片描述
原始碼

import time

r = ['.    ','. .  ','. . .']
for i in range(10):
    print("\r", r[i%3], end='', flush=True)
    time.sleep(0.4
)

時間進度條

效果截圖
在這裡插入圖片描述
原始碼

import datetime
import time

class Time():
    def __init__(self):
        self.one_second = datetime.timedelta(seconds=1)
        self.format = '%H:%M:%S'
 
    def add(self, cur):
        cur_format = datetime.datetime.strptime(cur, self.format)
        new_time = cur_format + self.
one_second return str(new_time.strftime(self.format)) def str_time(self, var3): a, b, c = [int(i) for i in var3.split(":")] a *= 3600 b *= 60 return a + b + c def percent(self, var1, var2): var1 = self.str_time(var1) var2 = self.
str_time(var2) return '{:.2%}'.format(var1/var2) def Timer(dest): total = Time() start = "00:00:00" while True: if dest == start: break start = total.add(start) print('\r%s/%s (%s)' % (start, dest, total.percent(start, dest)), end='') time.sleep(1) Timer("01:03:02")

#字進度條

效果截圖
在這裡插入圖片描述
原始碼

#!/usr/bin/env python3
import time
 
 
class Progress(object):
    def __init__(self, number=50, decimal=2):
        '''
        decimal 保留的保留小數位
        number #號個數
        '''
        self.decimal = decimal
        self.number = number
        self.a = 100/number   # 一個#號代表多少個百分比
 
    def __call__(self, cur, total):
        # 獲取當前的百分比數
        percentage = self.cal_percent(cur, total)
 
        # 根據現在百分比計算,應該有多少個#號,向下取整
        well_num = int(percentage / self.a)
 
        # 實現進度條
        result = "\r%s %s%%" % (self.progress_bar(well_num), percentage)
        return result
 
    def cal_percent(self, cur, total):
        '''
        cur:  現在的輪數
        total:  總輪數
        '''
        # round保留decimal位
        return round(cur / total * 100, self.decimal)
 
    def progress_bar(self, num):
        '''
        顯示進度條
        num 應顯示的#號個數
        '''
        # 空格個數
        space_num = " " * (self.number - num)
 
        return '[%s%s]' % ("#" * num, space_num)
 
 
 
index = Progress()
 
# 總輪數
Round_num = 371
for i in range(Round_num + 1):
    print(index(i, Round_num), end='')
    time.sleep(0.01)
    # \r 返回本行開頭
    # end : python 結尾不加任何操作, 預設是空格