tqdm 不可用时的简单回退进度条

gau*_*teh 3 python fallback progress tqdm

我有一个使用tqdm进度条的 python 包。但是,我不希望这成为我的包用户的硬依赖。是否有一些简单的插入式解决方案可以很容易地作为后备,如果tqdm没有安装?

我正在使用 的totalleave属性tqdm.tqdm(),以及实例的updateclose方法tqdm.tqdm

Pat*_*ick 5

当然。

def noobar(itrble, desc):
  """Simple progress bar. To be used if tqdm not installed."""
  L  = len(itrble)
  print('{}: {: >2d}'.format(desc,0), end='')
  for k,i in enumerate(itrble):
    yield i
    p = (k+1)/L
    e = '' if k<(L-1) else '\n'
    print('\b\b\b\b {: >2d}%'.format(int(100*p)), end=e)
    sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

试试看

from time import sleep
for i in noobar(range(5),"my work"):
  sleep(1)
Run Code Online (Sandbox Code Playgroud)