docker-compose 不在 Python 应用程序中打印标准输出 [英] docker-compose not printing stdout in Python app

查看:38
本文介绍了docker-compose 不在 Python 应用程序中打印标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在由 Docker Compose 管理的 Docker 容器内运行的 Python 应用程序中使用 print() 语句时,仅记录 sys.stderr 输出.没有看到 Vanilla print() 语句,所以:

When using a print() statement in a Python app running inside a Docker container that's managed by Docker Compose, only sys.stderr output is logged. Vanilla print() statements aren't seen, so this:

print("Hello? Anyone there?")

... 永远不会出现在常规日志中:

... never shows up in the regular logs:

(您可以在我的应用程序中看到其他库显式打印的其他日志,但没有我自己的调用.)

(You can see other logs explicitly printed by other libs in my app, but none of my own calls.)

如何避免我的 print() 调用被忽略?

How can I avoid my print() calls being ignored?

推荐答案

默认情况下,Python 将输出缓冲到 sys.stdout.

By default, Python buffers output to sys.stdout.

有几个选项:

1.调用显式flush

重构原始打印语句以包含一个 flush=True 关键字,例如:

Refactor the original print statement to include a flush=True keyword, like:

print("Hello? Anyone there?", flush=True)

注意:这将导致整个缓冲区刷新,而不仅仅是相同的打印调用.因此,如果其他地方存在未明确无缓冲的裸"打印函数调用(即没有 flush=True),它们也将始终被刷新.

Note: This will cause the entire buffer to flush, not just the same print call. So if there are 'bare' print function calls elsewhere (i.e. without flush=True) that weren't explicitly unbuffered, these will always be flushed too.

您可以通过以下方式实现相同的目的:

You could achieve the same thing with:

import sys
sys.stdout.flush()

如果您想最大程度地控制何时刷新,此选项很有用.

This option is useful if you want the most control of when the flushing will occur.

2.通过 PYTHONUNBUFFERED env var

2. Unbuffer the entire app via the PYTHONUNBUFFERED env var

将以下内容放入 docker-compose.yml 文件的 environment 部分:

Drop the following into the environment section of your docker-compose.yml file:

PYTHONUNBUFFERED: 1

这将导致 stdout 的所有输出立即被刷新.

This will cause all output to stdout to be flushed immediately.

3.使用 -u

与上面的选项 #2 一样,这将导致 Python 在应用程序的整个执行生命周期内无缓冲"地运行.只需使用 python -u 运行 - 不需要环境变量.

Like option #2 above, this will cause Python to run 'unbuffered' across the full execution lifetime of your app. Just run with python -u <entrypoint.py> - no need for the environment variable.

这篇关于docker-compose 不在 Python 应用程序中打印标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆