docker-compose在Python应用程序中不打印标准输出 [英] docker-compose not printing stdout in Python app
问题描述
在由Docker Compose管理的Docker容器中运行的Python应用程序中使用 print()
语句时,仅 sys.stderr
输出被记录。 Vanilla print()
语句未显示,因此:
print(你好?有人吗?)
...永远不会显示在常规日志中:
(您可以看到其他由...明确打印的日志
如何避免我的 print()
默认情况下,Python将输出缓冲存储到 sys.stdout
。
有几种选择:
1。调用显式 flush
重构原始打印语句以包含 flush = True
关键字,例如:
print( Hello?有人吗?,flush =是的)
注意:这将导致刷新整个缓冲区,而不是只是相同的打印通话。因此,如果在其他地方(即没有 flush = True
的地方)存在裸露的打印函数调用,而这些调用并未明确地未缓冲,则这些调用也将始终被刷新。 b
$ b
您可以使用以下方法实现相同的目的:
import sys
sys。 stdout.flush()
如果希望最大程度地控制 when 将发生冲洗。
2。通过 PYTHONUNBUFFERED
env var
取消缓冲整个应用程序,将以下内容放入<$ c $ docker-compose.yml
文件的c> environment 部分:
PYTHONUNBUFFERED:1
这将导致所有输出到 stdout
到
3。使用 -u
运行Python,就像上面的选项2,这将导致Python运行在应用的整个执行生命周期中保持无缓冲状态。只需使用 python -u< entrypoint.py>
运行-不需要环境变量。
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.)
How can I avoid my print()
calls being ignored?
By default, Python buffers output to sys.stdout
.
There are a few options:
1. Call an explicit flush
Refactor the original print statement to include a flush=True
keyword, like:
print("Hello? Anyone there?", 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. Unbuffer the entire app via the PYTHONUNBUFFERED
env var
Drop the following into the environment
section of your docker-compose.yml
file:
PYTHONUNBUFFERED: 1
This will cause all output to stdout
to be flushed immediately.
3. Run python with -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屋!