Py学习  »  Python

使用python脚本的docker中的尾部堆栈

amit • 5 年前 • 1349 次点击  

我试图用简单的python脚本构建docker,从文件中读取并打印它。
我希望python脚本将继续从文件中读取,因为文件中可能有新的数据。
但是当 文件不存在 当脚本启动时,tail似乎不工作,也不读取文件。
下面是一个简单的例子:

停靠文件 (不注释以说明问题)

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"]

主.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)

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

--编辑--
我尝试在第一个读行之后添加出口(1)以消除缓冲区问题。
结果几乎相同:
当命令命令容器退出时(退出代码1)
但是,当线路不命令时,容器根本不会退出(可能是从管道上读取)。
主.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文件,也会出现此问题:
停靠文件

FROM ubuntu:18.10
#RUN touch /tmp/file
CMD "tail" "-c-1" "-F" "/tmp/file"
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49642
 
1349 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Dmitrii
Reply   •   1 楼
Dmitrii    6 年前

这是已知的行为,这个问题与零大小的文件有关,如果您尝试使用 tail -f 在容器中,您将看到相同的行为。相同的 topic 解释原因。

这个零文件存在的选项是合成的,在现实生活中,真实的流创建具有内容的文件,所以这就是为什么这个问题在互联网上不那么流行。

正如在主题中提到的,您需要验证文件是否存在,大小是否为零。

jgoday
Reply   •   2 楼
jgoday    6 年前

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