首页 > 解决方案 > FileNotFoundError:[Errno 2] 没有这样的文件或目录:docker

问题描述

我正在尝试在 docker 容器中创建和写入文件。python 脚本在我的本地机器上运行良好,但我不知道如何让它在 docker 中运行。我使用官方 docker 文档创建了 app.py 和 dockerfile。

然后我用docker volume create my-vol 创建了一个卷。hello world 方法运行良好。这是文件:

Dockerfile

# syntax=docker/dockerfile:1
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

码头工人-compose.yml

version: "3.9"  # optional since v1.27.0
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - my-vol
volumes:
  logvolume01: {}

应用程序.py

app = Flask(__name__)
@app.route('/api/hello')
def hello_world():
    return 'Hello, Docker!'
    

@app.route('/api/ask')
def ask():
    try:
        my_file=open("/my-vol/newfile.txt","r")
        print(my_file.read())
        newString=input("Ingresa un nuevo string")
        new_file=open("/my-vol/newfile.txt",mode="w",encoding="utf-8")
        new_file.write(newString)
        new_file.close()
        my_file=open("/my-vol/newfile.txt","r")
        print(my_file.read())
    except IOError:
        new_file=open("/my-vol/newfile.txt",mode="w",encoding="utf-8")
        new_file.write("Archivo creado exitosamente \n")
        new_file.close()
        my_file=open("/my-vol/newfile.txt","r")
        print(my_file.read())
    finally:
        print("exit")

追溯

Traceback (most recent call last):
  File "/app/app.py", line 12, in ask
    my_file=open("/my-vol/newfile.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: '/my-vol/newfile.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/app/app.py", line 21, in ask
    new_file=open("/my-vol/newfile.txt",mode="w",encoding="utf-8")
FileNotFoundError: [Errno 2] No such file or directory: '/my-vol/newfile.txt'
172.17.0.1 - - [20/Aug/2021 10:59:32] "GET /api/ask HTTP/1.1" 500 -

标签: pythondockerdocker-composedockerfile

解决方案


问题是缺少/my-vol文件夹。它在异常处理程序内部并except再次在块中引发。您评论说它无法打开它以供阅读,但实际上却无法尝试编写它。

首先检查该文件夹是否存在,如果不存在则创建它。

旁注:将此类代码放入异常处理程序中确实是一种不好的做法。您通常只需在except块内设置一些标志并关心 try..except 块之外的问题。

在单个 try 块中放置这么多代码也是不好的做法,您只需将尽可能少的代码放在那里。


推荐阅读