類似 tqdm[1] 的東西,效果:
[ <NOW> / <TOTAL> ]
式簡易進度條。支持自定義前綴信息,形如:<MESSAGE>: [ <NOW> / <TOTAL> ]
;TypeError: object of type 'generator' has no len()
,不支持,但 tqdm 支持。原理就是不換行、並用 \r
重寫行。
import time
import numpy as np
from collections.abc import Iterable
def prog_bar(iter_obj, prefix=None):
"""simple progress bar (better NOT to use `print` inside) Input: - iter_obj: iter_obj: range, tuple, list, numpy.ndarray - prefix: str, some message to show Ref: - https://stackoverflow.com/questions/3002085/how-to-print-out-status-bar-and-percentage """
if isinstance(iter_obj, range):
_start, _stop, _step = iter_obj.start, iter_obj.stop, iter_obj.step
elif isinstance(iter_obj, Iterable):
_start, _stop, _step = 0, len(iter_obj), 1
else:
raise NotImplemented
n_digit = len(str(_stop))
if prefix != None:
template = "\r{}: [ %*d / %*d ]".format(prefix)
else:
template = "\r[ %*d / %*d ]"
print("", end="")
print(template % (n_digit, _start, n_digit, _stop), end="")
for i, x in enumerate(iter_obj):
yield x
print(template % (n_digit, _start + (i + 1) * _step, n_digit, _stop), end="")
print(template % (n_digit, _stop, n_digit, _stop))#, end="")
print("abcd")
for i in prog_bar(range(12, 103, 10)):
time.sleep(1)
print("efg")
print("hijk")
for x in prog_bar([1, 2, 3], "list"):
time.sleep(1)
print("lmn")
print("opq")
for x in prog_bar((4, 5, 6), "tuple"):
time.sleep(1)
print("rst")
print("uvw")
for x in prog_bar(np.array([[7, 8, 9], [10, 11, 12]]), "np.ndarray"):
time.sleep(1)
print("xyz")