k8s pod log日志不显示python print打印的内容
  JzPQ28Zr0PPv 2023年11月02日 69 0

问题

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   100   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   70   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   38   0   0 Python
  YpHJ7ITmccOD   2024年05月17日   39   0   0 Python
JzPQ28Zr0PPv