Suppose I have a file called handler.py
inside a docker container (which is not yet running or up from image). Let the image name be testimage
.
Inside handler.py
, we have a function greet
such that
def greet(username):
print("Hello %s!"%(username))
Now I want to start my docker container from this image such that I invoke this function greet
inside the file handler.py
along with an argument. I want to call this while creating a running container itself.
When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.
Docker ENTRYPOINT Unlike CMD commands, ENTRYPOINT commands cannot be ignored or overridden—even when the container runs with command line arguments stated. A Docker ENTRYPOINT instruction can be written in both shell and exec forms: Exec form: ENTRYPOINT [“executable”, “parameter1”, “parameter2”]
Step 1: Create a script.sh file and copy the following contents. Step 2: You should have the script.sh is the same folder where you have the Dockerfile. Create the Dockerfile with the following contents which copy the script to the container and runs it part of the ENTRYPOINT using the arguments from CMD.
Actually you're asking two things. One how to call a function in a python file from commandline. Two how to do this via Docker.
For the first, in the handler.py you'd need a main function to be able to do this. Something like this for example.
import sys
def greet(username):
print("Hello %s!"%(username))
if __name__ == '__main__':
greet(sys.argv[1])
Running it gives:
$ python handler.py harshvardhan
Hello harshvardhan!
Alternative and more complex is using OptionParser and switches based on that. Depending on your usecase, either works.
For the docker, I think you don't want to change the entrypoint, but the CMD. Dockerfile:
FROM python:2.7-alpine
WORKDIR /app
COPY handler.py .
ENTRYPOINT ["/usr/local/bin/python2.7"]
CMD ["/app/handler.py"]
Build an image:
$ docker build . -t local:dev
Run it, overriding the CMD
:
$ docker run local:dev /app/handler.py itismemario
Hello itismemario!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With