gpt4 book ai didi

python - Docker 容器仅在退出时打印输出

转载 作者:太空宇宙 更新时间:2023-11-04 11:19:37 31 4
gpt4 key购买 nike

我写了一个 python 程序及其 Dockerfile:

import time
print("Begin")
time.sleep(100);
print("End")

它的图像已创建,并使用 docker run <image-id> 运行令我惊讶的行为是,在控制台中给出运行命令后,它等待 sleep(100) 秒并打印 "Begin""End"在一起。

为什么我们在运行时没有得到中间结果?

另外,如果它不会在生成后立即发送数据,我该如何编写一个流式应用程序(在 kafka 左右)?

最佳答案

当您从控制台运行 Python 脚本时,它会在 stdout 上显示 Begin马上因为它是一个 tty(交互式)并在 end of each line 刷新.但是如果你像这样重定向 stdoutstdin python /tmp/a.py < /dev/null | cat , python 脚本不会注意到它是从 tty 运行的,并且只会在它完成时刷新。

如果你run the same script from a docker container , 它默认没有 tty,你必须明确要求一个 --tty , -t Allocate a pseudo-TTY :

docker run -t yourimage

或者,如果您不希望容器使用 tty 运行,您可以强制 flush通过设置 PYTHONUNBUFFERED 无论如何都会发生环境变量,通过添加 -u python 解释器的选项或像这样修改脚本:

import sys
import time
print("Begin")
sys.stdout.flush()
time.sleep(100);
print("End")

或使用 flush argument (仅限 python3):

import time
print("Begin", flush=True)
time.sleep(100);
print("End")

关于python - Docker 容器仅在退出时打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56293972/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com