簡體   English   中英

如何從 docker 容器中的 python 代碼中讀取本地目錄中的文件?

[英]how to read a file from a local directory from python code in a docker container?

我試圖將我的 python 代碼容器化,這正在工作,構建 docker 映像,運行容器並在我的 app.py 文件中調用 python 代碼。 接下來,我希望能夠上傳我的 python 代碼從應用程序的根目錄讀取以處理一些數據的 sample.txt 文件,下例中的 sample.txt。 但是這個文件需要更新,我希望能夠更新這個文件並運行容器,而不構建圖像。 我如何創建/掛載一個目錄並將 csv 文件放在那里並給出我的 python 代碼的路徑?

應用程序.py

import pandas as pd
print pd.read_csv('sample.csv')
...

泊塢窗文件

# Dockerfile
FROM debian:10.3-slim

WORKDIR /app

RUN apt-get update && apt-get -y dist-upgrade

RUN apt-get -y install apt-utils \
    build-essential \
    python3 \
    gcc \
    python3-dev \
    python3-pip \
    python3-numpy \
    python3-pandas

COPY requirements.txt /app/requirements.txt
RUN pip3 install -r requirements.txt

# Copy the python script
COPY modbus_to_influx.py /app/modbus_to_influx.py

CMD ["python3", "app.py"]

要求.txt

numpy 
pandas

當您docker run時,您可以(綁定)將主機上的文件夾/文件掛載為容器上的文件夾/文件:

docker run \
--interactive --tty --rm \
--volume=/path/to/host/file:/path/to/container/file \
your-container

例如,如果您在主機的根目錄中有example.csv ,並且您希望/data容器中的 Python 應用程序可以訪問它,您將:

docker run \
--interactive --tty --rm \
--volume=/example.csv:/data/example.csv \
your-container

注意文件名必須包含在--volume=host-path:container-pathhost-pathcontainer-path元素中,允許您將主機的文件 ( example.csv ) 重命名為容器上的其他內容。

或者您可以使用docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- https://docs.docker.com/engine/reference/commandline/cp/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM