程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python手寫簡易進度條

編輯:Python

類似 tqdm[1] 的東西,效果:

  • 打印 [ <NOW> / <TOTAL> ] 式簡易進度條。支持自定義前綴信息,形如:<MESSAGE>: [ <NOW> / <TOTAL> ]
  • 用法類似 tqdm,可套在 range、list、tuple、numpy.ndarray 上面用 for 遍歷。手寫的 generator 會報錯:TypeError: object of type 'generator' has no len()支持,但 tqdm 支持。

原理就是不換行、並用 \r 重寫行。

Code & Example

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")

References

  1. tqdm/tqdm
  2. How to print out status bar and percentage?
  3. Python腳本報錯:DeprecationWarning: Using or importing the ABCs from ‘collections’ instead of from ‘collections.abc’ is deprecated since Python 3.3,and in 3.9 it will stop working import pymssql

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved