Python控制檯輸出時重新整理當前行內容而不是輸出新行的實現
阿新 • • 發佈:2020-02-22
需求目標
執行Python程式的時候在控制檯輸出內容的時候只顯示一行,然後自動重新整理內容,像這樣:
Downloading File FooFile.txt [47%]
而不是這樣:
Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%]
實現環境
Python 3.x
實現程式碼
import time for i in range(10): time.sleep(0.2) print ("\r Loading... ".format(i)+str(i),end="")
這裡主要用到了Python 3.x裡面print函式增加的功能,使用\r可以重新整理當前行輸出,2.x裡面沒有測試,理論上不可以這樣操作
拓展知識:
python 覆蓋輸出/單行輸出方式
有時候看輸出進度時,會分別輸出進度,也就是輸出一長串數字,如果能夠覆蓋之前的輸出視覺效果會更好。
import sys import time for i in range(1000): percent = 1.0 * i / 1000 * 100 sys.stdout.write("\r nihao: %d / %d" %(percent,100)) sys.stdout.flush() time.sleep(0.1)
以上這篇Python控制檯輸出時重新整理當前行內容而不是輸出新行的實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。