1、問題描述 在Python中使用print打印hello world時,終端不顯示 1 2 | def hello():
print ( "hello world!" )
|
2、原因 因為標準輸入輸出stdin/stdout有緩沖區(qū),所以使用print不能立即打印出來,作為剛接觸Python的菜鳥,迷瞪了半天 3、解決方法 1)刷新緩沖區(qū),python中是sys.stdout.flush() 1 2 3 4 | import sys
def hello():
print ( "hello world!" )
sys.stdout.flush()
|
2)python3中支持print支持參數(shù)flush 原型: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
1 2 | def hello():
print ( "hello world!" , flush = True )
|
參考官方手冊 https://docs./zh-cn/3/library/functions.html#print Python控制臺輸出時刷新當前行內(nèi)容而不是輸出新行的實現(xiàn)需求目標 執(zhí)行Python程序的時候在控制臺輸出內(nèi)容的時候只顯示一行,然后自動刷新內(nèi)容,像這樣: Downloading File FooFile.txt [47%]
而不是這樣: 1 2 3 | Downloading File FooFile.txt [ 47 % ]
Downloading File FooFile.txt [ 48 % ]
Downloading File FooFile.txt [ 49 % ]
|
實現(xiàn)環(huán)境 Python 3.x 實現(xiàn)代碼 1 2 3 4 | import time
for i in range ( 10 ):
time.sleep( 0.2 )
print ( "\r Loading... " . format (i) + str (i), end = "")
|
這里主要用到了Python 3.x里面print函數(shù)增加的功能,使用\r可以刷新當前行輸出,2.x里面沒有測試,理論上不可以這樣操作 拓展知識: python 覆蓋輸出/單行輸出方式 有時候看輸出進度時,會分別輸出進度,也就是輸出一長串數(shù)字,如果能夠覆蓋之前的輸出視覺效果會更好。 1 2 3 4 5 6 7 8 9 | 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 )
|
https://blog.csdn.net/lpwmm/article/details/82926099
|