gpt4 book ai didi

python - 使用python脚本的docker中的尾栈

转载 作者:行者123 更新时间:2023-12-02 18:36:34 24 4
gpt4 key购买 nike

我正在尝试使用简单的python脚本构建docker从文件中读取并打印它。
我希望python脚本将继续从文件中读取,因为文件中可能有新数据。
但是,当脚本启动时,如果文件不存在,则tail似乎不起作用并且无法读取该文件。
这是简单的示例:

dockerfile (注释以说明问题)

FROM ubuntu:18.10
RUN apt-get update && apt-get install -y --no-install-recommends python3 && rm -rf /var/lib/apt/lists/*
#RUN touch /tmp/file # uncomment will cause the problem
COPY . /app/
CMD ["python3","/app/main.py"]

main.py
import subprocess
argsList = ['tail', '-c-1', '-F', '/tmp/file']
f = subprocess.Popen(argsList, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
line = f.stdout.readline()
while line != b'':
line = f.stdout.readline().decode("utf-8")
print(line)

如果我输入docker(当没有 / tmp / file时输入 )并开始写入该文件(使用echo“text” >> / tmp / file),我可以在docker屏幕中查看输出。
但是,如果我取消注释dockerfile中的触摸注释(导致创建/ tmp / file),尽管我使用相同的命令,但我无法在docker屏幕中看到任何输出(回显“text” >> / tmp /文件)。
为什么会有这样的差异,即使文件存在,我怎么也能看到输出?

-编辑-
我试图在第一条读取行之后添加exit(1)来消除缓冲区问题。
结果几乎相同:
当该行是命令行时,容器按预期方式退出(退出代码为1)
但是当该行中断时,该容器根本不会退出(可能停留在从管道读取的位置)。
main.py
import subprocess
argsList = ['tail', '-c-1', '-F', '/tmp/file']
f = subprocess.Popen(argsList, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
line = f.stdout.readline()
exit(1)

-编辑2-
如果只有docker文件,也会发生此问题:
dockerfile
FROM ubuntu:18.10
#RUN touch /tmp/file
CMD "tail" "-c-1" "-F" "/tmp/file"

最佳答案

打印后尝试使用sys.stdout.flush(),以强制将输出缓冲区也打印在屏幕上。它似乎对我有用(相同的dockerfile和脚本)

关于python - 使用python脚本的docker中的尾栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55191151/

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