66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
# @File : progress.py
|
|
# @Time : 2026/04/12 22:20:53
|
|
# @Author : SilverAg.L
|
|
|
|
from shutil import get_terminal_size
|
|
from sys import stdout
|
|
|
|
|
|
class RawProgressBar:
|
|
def __init__(self, total=100, unit='%', bar_format=None, **kwargs):
|
|
self.total = total
|
|
self.unit = unit
|
|
self.n = 0
|
|
self.cols = get_terminal_size((40, 20)).columns
|
|
self.bar_format = bar_format # unused
|
|
|
|
def update(self, delta):
|
|
self.n += delta
|
|
self.refresh()
|
|
|
|
def refresh(self):
|
|
cur = min(self.n, self.total)
|
|
pct = min(cur / self.total if self.total > 0 else 0, 1.0)
|
|
pct_str = f"{pct * 100:3.0f}%"
|
|
rate_str = f"{cur:.2f}/{self.total:.2f}({self.unit})"
|
|
fixed_len = len(pct_str) + len(rate_str) + 10
|
|
bar_width = max(self.cols - fixed_len, 10)
|
|
filled_len = int(bar_width * pct)
|
|
bar = '>' * filled_len + '-' * (bar_width - filled_len)
|
|
output = f"\r {pct_str} [{bar}] {rate_str}".ljust(self.cols)
|
|
stdout.write(output)
|
|
stdout.flush()
|
|
|
|
def close(self):
|
|
stdout.write('\n')
|
|
stdout.flush()
|
|
|
|
|
|
try:
|
|
from tqdm import tqdm
|
|
|
|
def get_progress_bar(total, unit, bar_format=None):
|
|
return tqdm(file=stdout, total=total, unit=unit, bar_format=bar_format)
|
|
except ImportError:
|
|
def get_progress_bar(total, unit, bar_format=None):
|
|
return RawProgressBar(total=total, unit=unit, bar_format=bar_format)
|
|
|
|
|
|
def is_tty():
|
|
return stdout.isatty()
|
|
|
|
|
|
def test_progress_bar():
|
|
from time import sleep
|
|
pbar = get_progress_bar(total=100, unit='%')
|
|
for i in range(101):
|
|
sleep(0.1)
|
|
pbar.n = i
|
|
pbar.refresh()
|
|
pbar.close()
|
|
print("Done!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_progress_bar()
|