This answer is kind of late but for any future readers, i would like to make it more towards the question asked i.e. with respect to argparse.
The basic idea like @Chris pointed out is it. One way to achieve the solution is to pass arguments to the image
in docker run command itself. These arguments would then be passed to your ENTRYPOINT
, therefore passing to the python script.
The files would look something like this typically..
file.py
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('pos', type=str, help='Example Positional Argument') # will be accesible under args.POS
parser.add_argument('--opt', type=str , help='Example Optional Argument') # will be accesible with args.OPT
args = parser.parse_args()
# do something with pos and OPT
Without docker, You would run this file (assuming it is in the pwd) as python file.py --opt opt_val pos_val
Dockerfile
FROM python:<your_tag>
COPY ./file.py ./ # Assuming your Dockerfile and file.py are in the same directory
# some custom build steps
ENTRYPOINT ["python","./file.py"]
Docker build and run commands
You build with this : docker build --tag example:0.0.1 <dir>
The below shows multiline(for better readability) run commands,
Docker run
docker run --rm \
--name example.container \
example:0.0.1 \
--opt=opt_val \
POS=pos_value
Docker run (powershell)
docker run --rm `
--name example.container `
example:0.0.1 `
--opt=opt_val `
POS=pos_value
So here are some points to remember:
- Argparse has support for adding positional and optional arguments and should be passed accordingly to the
image
in the docker run
command.
- The solution pointed out above works but is not as flexible as id generally like it to be. Better to use Environment variables and access inside the script with
os.environ()
.
- With this solution you dont "hard-code" anything to the Dockerfile