1. 程式人生 > 程式設計 >Python print不能立即列印的解決方式

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

1、問題描述

在Python中使用print列印hello world時,終端不顯示

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

2、原因

因為標準輸入輸出stdin/stdout有緩衝區,所以使用print不能立即打印出來,作為剛接觸Python的菜鳥,迷瞪了半天

3、解決方法

1)重新整理緩衝區,python中是sys.stdout.flush()

import sys 
def hello():
 print("hello world!")
 sys.stdout.flush()

2)python3中支援print支援引數flush

原型:

print(*objects,sep=' ‘,end='\n',file=sys.stdout,flush=False)

def hello():
 print("hello world!",flush=True)

參考官方手冊

https://docs.python.org/zh-cn/3/library/functions.html#print

以上這篇Python print不能立即列印的解決方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。