問題
Python 程式代碼中使用 print() 列印的內容,在查詢 k8s pod 日志時不顯示,
原因
print() 函式
Python 的 print() 函式簽名如下:
print(*objects, sep=' ', end='\n', file=None, flush=False)
摘錄部分官方檔案如下:
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
由于沒有顯式地傳遞 file 引數,所以 Python 會默認使用 sys.stdout
sys.stdout
查閱官方檔案,節選片段:
When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable.
stdout是有快取的,只有遇到換行或者積累到一定的大小,才會顯示出來,
解決方案
解決方案在 envvar-PYTHONUNBUFFERED 中其實已經說明了,有兩種:
- 設定環境變數
PYTHONUNBUFFERED - 運行 python 程式時,使用
-u命令選項
在 Dockerfile 中我們只需這樣一行設定即可:
ENV PYTHONUNBUFFERED=1
參考
- print(*objects, sep=' ', end='\n', file=None, flush=False)
- sys.stdout
- envvar-PYTHONUNBUFFERED
- Dockerfile env

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548701.html
標籤:Python
