Docker Community Forums

Share and learn in the Docker community.

Best way to run Python script then stop container

Hello,

I want to allow non-technical people in my project to run Python scripts on their laptop without having them to setup the necessary technical environment (virtual environment, packages, dependencies etc).

I want them for instance to be able to use a command ./merge.sh, so that the script can start the docker container, mount a local directory as a volum (to get the input and the output), run the Python script, stop the container.

I want to be able to do so for different commands (for instance also ./transform.sh, ./encode.sh)…

What is the best way to make this happen, both from a technical point of view (extensible, maintainable) and a usage point of view (only need to install docker/docker-compose and clone my repository).

Thanks

I have made functions that uses the python image to run a python script in the current directory. I use (more or less) the line from the official pyton image documentation. Something like this:

# Functions
py3() {
  docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:3 python $1
}

py2() {
  docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:2 python $1
}
1 Like

One solution would be using a Makefile, providing GNU make is installed. This way, you can write modular recipes.


.PHONY: pull run transform encode

ROOT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
IMAGE := "guillaumedesforges/python_image:latest"

pull:
	docker pull $(IMAGE)

run:
	docker run -it -v "$(ROOT_DIR)":/usr/src/myapp -w /usr/src/myapp $(IMAGE) python $(CMD)

transform:
	$(MAKE) run CMD="./transform.py"

encode:
	$(MAKE) run CMD="./encode.py"

Your colleagues may then invoke very simple commands from a shell:

$ make pull # executed once
$ make transform
$ make encode

Voilà ! :slight_smile:

1 Like

Nice one pinimo! I’ll “steal” that. :smiley: