2023-03-30 11:44阅读: 608评论: 0推荐: 0

k8s pod log日志不显示python print打印的内容

问题

Python 程序代码中使用 print() 打印的内容,在查询 k8s pod 日志时不显示。

原因

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

参考


image

本文作者:暮重云

本文链接:https://www.cnblogs.com/fengyinxu/p/python-print-no-show-in-k8s-pod-log.html

版权声明:本作品采用【知识共享署名-非商业性使用-禁止演绎4.0国际】许可协议进行许可。

posted @   暮重云  阅读(608)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起