让Docker映像与主机环境进行交互

我真的需要docker帮助。

我的docker文件如下:

FROM python:3-alpine

LABEL author="alaa"
LABEL description="Dockerfile for Python script which generates emails"
RUN pip install tqdm
COPY email_generator.py /app/
CMD python3 /app/email_generator.py

我的pthon代码如下:

import json  # to read json files
import os  # to access operation for get and changing directory


def writeTextFile(text,index):
    f = open(ziel + '/email_%s.txt' % index,'w+')
    f.write(text)
    f.close()


def writeHashFile(text):
    f = open(ziel + '/00_Hash.json','w+')
    f.write(str(text))
    f.close()


def readJsonCordinate(fileName):
    """Read the json data."""
    with open(fileName,'r',encoding='utf-8') as f:  # Opening the file
        data = json.load(f)  # Read the json file
    return data

以此类推...

我的问题是,如果要在构建映像后从主机系统获取文件,则会出现此错误。但是,如果我在macOS的pycharm上天真地运行代码,它将运行完美

Traceback (most recent call last):
  File "/app/email_generator.py",line 112,in <module>
    betreff = readJsonCordinate(quelle + '/Betreff.json')
  File "/app/email_generator.py",line 22,in readJsonCordinate
    with open(fileName,encoding='utf-8') as f:  # Opening the file
FileNotFoundError: [Errno 2] No such file or directory: '/Users/soso/desktop/email_generator/Worterbuecher/Betreff.json'
web335 回答:让Docker映像与主机环境进行交互

这可能是因为您尚未将错误即将发生的文件复制到Docker中。

检查文件是否存在于Docker映像中

docker run -it --rm --entrypoint="" <image-name>:<image-tag> /bin/sh

并输入控制台:

find / -iname 'Betreff.json'

在图像中找到该文件,并在python中更改路径,使其与更新的路径一起工作

或者您可以通过以下方式使用-v标志将包含该文件的目录添加为映射目录:

docker run -v /Users/soso/desktop/email_generator/Worterbuecher/:/Users/soso/desktop/email_generator/Worterbuecher/ ... some other opitons <docker-image>:<docker-tag>

有关docker run command的更多信息,请查找-v或--volume选项以获取详细信息

,

您无法使用VM文件路径访问VM上的文件。

这是因为容器文件系统实际上已从VM文件系统断开连接。

您可以使用docker volumes将VM目录和文件映射到容器。

然后python程序将能够使用容器路径从容器内访问映射的文件和目录。

本文链接:https://www.f2er.com/3127877.html

大家都在问