k8s pod log日志不显示python print打印的内容
问题
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.cnblogs.com/fengyinxu/p/python-print-no-show-in-k8s-pod-log.html
版权声明:本作品采用【知识共享署名-非商业性使用-禁止演绎4.0国际】许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端