Python文件写入在Docker内部不起作用 [英] Python file writing is not working inside docker

查看:267
本文介绍了Python文件写入在Docker内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将其中包含文本文件和CSV文件的文件写入其中的python脚本码头化。


作为参考,我的代码是

  FROM python:3 



添加./HMS.py /
添加./constants.py /
添加./Docker.py /
添加./SNT.py /
添加./Utility.py /


运行pip install --trusted-host pypi.org --trusted-host文件。 pythonhosted.org docker
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org grepfunc
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org请求


CMD [ python, ./ HMS.py; ]

但是,当我在外部运行python脚本时,便能够生成文件。我可以知道为什么它没有在工作目录中生成。


UPDATE


  def write_log(self ,文件名,消息,类型='信息'):
,以open(文件名,'a')作为日志:
log.write('\n'+消息)

def write_csv(self,filepath,data):
with open(filepath,'a',newline ='')as file:
writer = csv.writer(file)
writer .writerow(data)

常量文件包含路径

  LOG_FILE ='。/ snt_alarm_log.txt'
COMPONENT_NAME ='SNT警报'
DB_FILE ='。/ snt.csv'


解决方案

容器本质上是短暂的。如果要保留容器内部生成的文件,则需要将主机文件系统挂载到容器的文件系统。挂载卷的方法有很多,但是常见的方法是绑定挂载

  docker run -v / path / to /主机:/ project sntalarmdocker_snt 

任何保存到 / project 也将显示在 / path / to / host 中。

I'm a trying to dockerize a python script in which file writing of a text file and CSV file is there. but it is not working, the file is not getting generated.

For reference my code is

FROM python:3



ADD ./HMS.py /
ADD ./constants.py /
ADD ./Docker.py /
ADD ./SNT.py /
ADD ./Utility.py /


RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org docker
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org grepfunc
RUN pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org requests


CMD [ "python", "./HMS.py" ]

However, when I run the python script outside am able to generate the files. May I know why it is not getting generated inside the work directory.

UPDATE

    def write_log(self, filename, message, type='info'):
        with open(filename, 'a') as log:
            log.write('\n' + message)

    def write_csv(self, filepath, data):
        with open(filepath, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(data)

constant file contain the path

LOG_FILE='./snt_alarm_log.txt'
COMPONENT_NAME='SNT Alarm'
DB_FILE='./snt.csv'

解决方案

Containers are ephemeral by nature. If you want to retain files generated inside a container you need to mount your host file system to the file system of the container. There are many ways to mount a volume, but a common way is a bind mount

docker run -v /path/to/host:/project sntalarmdocker_snt

Whatever gets saved to /project will be visible in /path/to/host even after the container is killed

这篇关于Python文件写入在Docker内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆