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

Python handwritten simple progress bar

編輯:Python

similar tqdm[1] Things that are , effect :

  • Print [ <NOW> / <TOTAL> ] Simple progress bar . Support custom prefix information , Form like :<MESSAGE>: [ <NOW> / <TOTAL> ];
  • Usage is similar. tqdm, Can be set on range、list、tuple、numpy.ndarray On it for Traverse . Handwritten generator Will report a mistake :TypeError: object of type 'generator' has no len(), No Support , but tqdm Support .

The principle is no line breaks 、 And use \r Rewrite row .

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 Script error :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