2018年12月31日 星期一

[ Python 常見問題 ] Text Progress Bar in the Console

Source From Here 
Question 
As title. How to draw a progress bar for long time execution task in command line mode? 

How-To 
For a hand-made version: 
  1. # Print iterations progress  
  2. def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):  
  3.     """  
  4.     Call in a loop to create terminal progress bar  
  5.     @params:  
  6.         iteration   - Required  : current iteration (Int)  
  7.         total       - Required  : total iterations (Int)  
  8.         prefix      - Optional  : prefix string (Str)  
  9.         suffix      - Optional  : suffix string (Str)  
  10.         decimals    - Optional  : positive number of decimals in percent complete (Int)  
  11.         length      - Optional  : character length of bar (Int)  
  12.         fill        - Optional  : bar fill character (Str)  
  13.     """  
  14.     percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))  
  15.     filledLength = int(length * iteration // total)  
  16.     bar = fill * filledLength + '-' * (length - filledLength)  
  17.     print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')  
  18.     # Print New Line on Complete  
  19.     if iteration == total:   
  20.         print()  
  21.   
  22. #   
  23. # Sample Usage  
  24. #   
  25.   
  26. from time import sleep  
  27.   
  28. # A List of Items  
  29. items = list(range(0, 57))  
  30. l = len(items)  
  31.   
  32. # Initial call to print 0% progress  
  33. printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)  
  34. for i, item in enumerate(items):  
  35.     # Do stuff...  
  36.     sleep(0.1)  
  37.     # Update Progress Bar  
  38.     printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)  
For a exist python package tqdm: add a progress meter to your loops in a second: 
  1. >>> import time  
  2. >>> from tqdm import tqdm  
  3. >>> for i in tqdm(range(100)):  
  4. ...     time.sleep(1)  
  5. ...  
  6. 27%|██████████████████████████████████                                                                                            | 27/100 [00:36<01:18,  1.08s/it]  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...