Python文件写入在Docker内部不起作用 [英] Python file writing is not working inside 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
任何保存到 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 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. / project $ c的内容即使在容器被杀死之后,$ c>也将显示在
/ path / to / host
中。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" ]
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屋!