小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python print不能立即打印的解決方式

 rongq2007 2020-08-06

1、問題描述

在Python中使用print打印hello world時(shí),終端不顯示

1
2
def hello():
 print("hello world!")

2、原因

因?yàn)闃?biāo)準(zhǔn)輸入輸出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控制臺輸出時(shí)刷新當(dāng)前行內(nèi)容而不是輸出新行的實(shí)現(xiàn)

需求目標(biāo)

執(zhí)行Python程序的時(shí)候在控制臺輸出內(nèi)容的時(shí)候只顯示一行,然后自動刷新內(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%]

實(shí)現(xiàn)環(huán)境

Python 3.x

實(shí)現(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可以刷新當(dāng)前行輸出,2.x里面沒有測試,理論上不可以這樣操作

拓展知識:

python 覆蓋輸出/單行輸出方式

有時(shí)候看輸出進(jìn)度時(shí),會分別輸出進(jìn)度,也就是輸出一長串?dāng)?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

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多