【451】python 同一行打印进度条
参考:\r\n, \r and \n what is the difference between them? [duplicate]
参考:python的print格式化输出,以及使用format来控制。
实现思路就是不停地删除之前打印的内容,通过 '\r' 实现光标返回最前,之后会覆盖内容,没被覆盖的还会继续显示。
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment\n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of\r
and\n
import sys,time # 变量 total = 153 for i in range(total): if i+1 == total: percent = 100.0 print('Progress: %s [%d/%d]'%(str(percent)+'%', i+1, total), end='\n') else: percent = round(1.0 * i / total * 100,2) print('Progress: %s [%d/%d]'%(str(percent)+'%', i+1, total), end='\r') # 将百分号与数字合并起来了 time.sleep(0.01)
上面 % 使用可以参考:【387】Python format 格式化函数(以及 %)
下面就是用最普通的方式写的,更好懂
import sys,time # 变量 total = 153 for i in range(total): if i+1 == total: percent = 100.0 print('Progress: '+str(percent)+'% ['+str(i+1)+'/'+str(total)+']', end='\n') else: percent = round(1.0 * i / total * 100,2) print('Progress: '+str(percent)+'% ['+str(i+1)+'/'+str(total)+']', end='\r') time.sleep(0.01)