51Testing软件测试论坛

标题: 好玩的Python库tqdm [打印本页]

作者: 测试积点老人    时间: 2018-12-14 17:17
标题: 好玩的Python库tqdm

可以显示循环的进度条的库,再也不用担心不知道程序跑到哪里还要跑多久了

tqdm()可以直接包裹iterable的对象

  1. from tqdm import tqdm,trange
  2. from time import sleep
  3. text = ""
  4. for char in tqdm(["a", "b", "c", "d"]):
  5.     text = text + char
  6.     sleep(0.1)
复制代码

trange(i)相当于tqdm(range(i))

  1. for i in trange(100):
  2.     sleep(0.01)
复制代码

可以在循环外面预先定义tqdm的对象

  1. pbar = tqdm(["a", "b", "c", "d"])
  2. for char in pbar:
  3.     pbar.set_description("Processing %s" % char)
复制代码

有两个参数比较有用,desc(str)和leave(bool)
desc可以指定这个循环的的信息,以便区分。上面的set_description(str)和这个应该是一样的。
leave则表示进度条跑完了之后是否继续保留

  1. for i in tqdm(range(10), desc='1st loop'):
  2.     for j in trange(100, desc='2nd loop', leave=False):
  3.         sleep(0.01)
复制代码

如果要在Jupyter Notebook上面使用,那么要把tqdm换成tqdm_notebook,trange换成tnrange

  1. from tqdm import tnrange, tqdm_notebook
  2. from time import sleep

  3. for i in tqdm_notebook(range(10), desc='1st loop'):
  4.     for j in tnrange(100, desc='2nd loop', leave=False):
  5.         sleep(0.01)
复制代码



作者: Miss_love    时间: 2021-1-5 16:59
支持分享




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2