python的print不能及時輸出的處理


1、問題描述

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

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

2、原因

因為標准輸入輸出stdin/stdout有緩沖區,所以使用print不能立即打印出來

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)

3)使用python啟動選項:

  -u忽略緩沖區

python -u xx.py

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM