1

I've seen this post, which covers "Passing file as argument to Docker container", and have followed that. But I'd like to be able to write out to a different file rather than overwriting the file that was passed in.

An example docker image:

FROM python:3.8-slim
RUN useradd --create-home --shell /bin/bash app_user
WORKDIR /home/app_user
USER app_user
# I guess I have to assume that this image is built wherever this module is...
COPY script.py .

where script.py contains (sorry if it's a bit long for what it is):

import sys 
import pathlib
import argparse


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="meh",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument(
            "-c",
            "--convert_file",
            type=str,
            help="Convert this file.",
        )

    parser.add_argument(
            "-o",
            "--output_file",
            type=str,
            help="Output converted file here.",
        )

    args = parser.parse_args()

    if args.convert_file:
        if not args.output_file:
            output_file = '/something.txt'
        else:
            output_file = args.output_file


        file_path = pathlib.Path(args.convert_file)
        text = pathlib.Path(file_path).read_text().upper()
        pathlib.Path(output_file).write_text(text)
    
    raise SystemExit()

And this can be run as:

docker run -v <abs path local system>/something.txt:/home/app_user/something.txt \
    -t app:latest \
    python -m script -c /home/app_user/something.txt -o /home/app_user/something.txt

where something.txt contains:

this is a test, should start lowercase and finish uppercase.

before running, and after running it contains:

THIS IS A TEST, SHOULD START LOWERCASE AND FINISH UPPERCASE.

So, it works to a degree, but instead of overwriting something.txt I'd like to be able to create something_upper.txt (or whatever).

So - how can I take a file as input to a docker container, and write out to a different file on the local system?

baxx
  • 3,956
  • 6
  • 37
  • 75
  • If the primary goal of the script is to read and write host files, a Docker container is a poor match: by design it wants to prevent the container process from modifying the host filesystem. Can you run this in a non-Docker Python virtual environment instead? – David Maze Mar 10 '22 at 21:35
  • @DavidMaze thanks - I would like to be able to have system dependencies captured by the container as well though, so for something with a very narrow focus docker seemed like it might be suitable? I was basically thinking of something that would act like a CLI tool, but it's a container. – baxx Mar 10 '22 at 21:43

0 Answers0