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.
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!
You can provide the python script execution command during docker run as below,
docker run <image> python handler.py --user username_value
.
And make sure you have handled that args using argparse in handler.py and call your greet function.
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--user', help='username', required=True, type=str)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.