简体   繁体   English

阐明如何在 Docker 中指定来自 Python 的文件路径

[英]Clarify how to specify file paths inside Docker coming from Python

I have created a Docker image with for a Flask app.我已经为 Flask 应用程序创建了 Docker 图像。 Inside my Flask app, this is how I specify the file paths.在我的 Flask 应用程序中,这就是我指定文件路径的方式。

dPath = os.getcwd() + "\\data\\distanceMatrixv2.csv"

This should ideally resolve in a filepath similar to app/data/distanceMatrixv2.csv .理想情况下,这应该在类似于app/data/distanceMatrixv2.csv的文件路径中解决。 This works when I do a py main.py run in the CMD .当我在 CMD 中运行py main.py时,此方法有效 After making sure I am in the same directory, creating the image and running the Docker image via docker run -it -d -p 5000:5000 flaskapp , it throws me the error below when I try to do any processing.在确保我在同一目录中,创建图像并通过docker run -it -d -p 5000:5000 flaskapp Docker 图像后,当我尝试进行任何处理时,它会抛出以下错误。

FileNotFoundError: /backend\data\distanceMatrixv2.csv not found.

I believe this is due to how Docker resolves file paths but I am a bit lost on how to "fix" this.我相信这是由于 Docker 如何解析文件路径,但我对如何“修复”这个问题有点迷茫。 I am using Windows while my Docker image is built with FROM node:lts-alpine .我正在使用Windows而我的 Docker 图像是使用FROM node:lts-alpine构建的。

node:lts-alpine is based on Alpine which is a Linux distro. node:lts-alpine基于 Linux 发行版 Alpine。 So your python program runs under Linux and should use Linux file paths, ie forward slashes like所以你的 python 程序在 Linux 下运行,应该使用 Linux 文件路径,即正斜杠

dPath = os.getcwd() + "/data/distanceMatrixv2.csv"

It looks like os.getcwd() returns /backend .看起来os.getcwd()返回/backend So the full path becomes /backend/data/distanceMatrixv2.csv .因此完整路径变为/backend/data/distanceMatrixv2.csv

The os.path library can do this portably across operating systems. os.path可以跨操作系统进行移植。 If you write this as如果你把它写成

import os
import os.path

dPath = os.path.join(os.getcwd(), "data", "distanceMatrixv2.csv")

it will work whether your (Windows) system uses DOS-style backslash-separated paths or your (Linux) system uses Unix-style forward slashes.无论您的 (Windows) 系统使用 DOS 样式的反斜杠分隔路径还是您的 (Linux) 系统使用 Unix 样式的正斜杠,它都可以工作。

Python 3.4 also added a pathlib library , if you prefer a more object-oriented approach.如果您更喜欢面向对象的方法,Python 3.4 还添加了一个pathlib This redefines the Python / division operator to concatenate paths, using the native path separator.这重新定义了 Python /除法运算符以连接路径,使用本机路径分隔符。 So you could also write所以你也可以写

from pathlib import Path

dPath = Path.cwd() / "data" / "distanceMatrixv2.csv"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM