我试图用简单的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"