【问题标题】:Writing Outputs Using Python In A Docker Container在 Docker 容器中使用 Python 编写输出
【发布时间】:2021-11-10 03:10:41
【问题描述】:

在构建 docker 映像 (docker_run_test) 后,我正在尝试将文本 (.txt) 文件写入 Windows 10 上的本地桌面文件夹。 docker build 似乎可以使用“docker build -t docker_run_test.”无缝运行,从 Dockerfile 和 Python 脚本所在的桌面上的工作目录运行命令(C:/Users/mdl518/Desktop/docker_tests/)。该脚本是一个简单的打印语句并将打印语句写入 .txt 文件,但我找不到输出 .txt。下面是相关的 Dockerfile 和 Python 脚本。

Dockerfile:

FROM python:3

ADD docker_test.py ./

RUN pip install pandas

CMD ["python3","./docker_test.py"]

Python 脚本 (docker_test.py):

import os

print("This is a Docker test.")

with open('docker_test.txt', 'w') as f:
    f.write("This is a Docker test.")

我也搜索了 Docker 镜像的内容,但也无法在镜像中找到输出的 .txt。非常感谢任何帮助!

【问题讨论】:

  • 文件将写入容器。脚本结束时容器停止​​。您应该挂载一个卷来与主机交换文件。
  • 看来你需要添加一个命令来阻止容器停止,然后你可以进入正在运行的容器查看文件

标签: python docker directory dockerfile docker-run


【解决方案1】:

您必须将要查看结果的文件夹挂载/绑定到容器中。

将输出文件名更改为写入另一个文件夹,比如/output

with open('/output/docker_test.txt', 'w') as f:

然后让Docker将主机文件夹%HOMEPATH%\Desktop绑定到容器/output

docker run -v %HOMEPATH%\Desktop:/output docker_run_test

我是 Linux 用户,不确定 %HOMEPATH% 语法。

【讨论】:

  • Benoit Courty 等人。 - 感谢您的进一步澄清,这完美地回答了我的问题,我现在可以访问本地目录中的输出文件!我会确认您的答案是正确的解决方案,再次感谢!
猜你喜欢
  • 1970-01-01
  • 2017-07-04
  • 2021-07-26
  • 1970-01-01
  • 2015-12-09
  • 2017-01-22
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多