日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

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

 rongq2007 2020-08-06

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

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

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多