繁体   English   中英

从 Dockerfile 执行的 Python 脚本不写入 HTML 文件

[英]Python script executed from Dockerfile doesn't write HTML file

我正在尝试在构建 docker 映像时更改一些 .html 文件。 我创建了一个 add_style.py,它改变了 html 以添加一行 css。 首先让我向您展示Dockerfile

FROM golang:1.15.2-buster as ClaatSetup
RUN CGO_ENABLED=0 go get github.com/googlecodelabs/tools/claat

FROM alpine:3.10 as ClaatExporter
WORKDIR /app
COPY --from=ClaatSetup /go/bin/claat /claat
COPY docs/ input/
RUN /claat export -o output input/**/*.md


FROM alpine:3.10 as AppCompiler
RUN apk add --update git nodejs npm make python gcc g++ && \
    npm install -g gulp-cli

WORKDIR /app

# against caching when there is a new commit
ADD "<..>" /tmp/devalidateCache
RUN git clone <..>
WORKDIR /app/codelabs-site

# Install dependencies
RUN npm install && npm install gulp

# Copy exported codelabs from previous stage
COPY --from=ClaatExporter /app/output codelabs/

# Build everything
RUN gulp dist --codelabs-dir=codelabs

# Replace symlink in with actual content (see below for description)
WORKDIR /app/codelabs-site/dist
RUN rm codelabs
COPY --from=ClaatExporter /app/output codelabs/



FROM caddy:alpine as Deployment
WORKDIR /app

COPY --from=AppCompiler /app/codelabs-site/dist/ .

#injecting of css to widen codelabs
RUN apk add --no-cache python3 py3-pip
RUN pip3 install bs4
COPY add_style.py codelabs/add_style.py
RUN python3 codelabs/add_style.py

EXPOSE 80
EXPOSE 443
CMD ["caddy", "file-server"]

然后 add_style.py 本身:

import os
from bs4 import BeautifulSoup, Doctype

for root, dirnames, filenames in os.walk(os.getcwd()):
    for filename in filenames:
        if filename.endswith('index.html'):
            fname = os.path.join(root, filename)
            print('Filename: {}'.format(fname))
            with open(fname, 'r+', encoding = 'utf-8') as handle:
                soup = BeautifulSoup(handle.read(), 'html.parser')
                head = soup.head
                head.append(soup.new_tag('style', type='text/css'))
                head.style.append('.instructions {max-width: 1000px;} #fabs {max-width: 1200px;}')
                   
                #write altered html
                handle.write(str(soup.prettify()))
                handle.flush()

后一个脚本运行完美,没有错误。 此外,如果您输出soup.prettify()它会显示添加了CSS 的更改后的html。 现在,如果我在同一个脚本中再次读取文件,它会显示旧版本。我尝试在 docker 构建的不同阶段执行此脚本,但它只是不写入文件。 没有显示错误..

正如@Armando 的评论。 解决方案是添加seek和truncate:

   #write altered html
   handle.seek(0)
   handle.write(str(soup.prettify()))
   handle.truncate()
   handle.flush()

暂无
暂无

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

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