Pass arguments to Python argparse within Docker container

前端 未结 3 1775
春和景丽
春和景丽 2020-12-28 08:42

I am embarking on my first attempt at utilizing a docker container. I have a python script that calls a couple API\'s and parses a file. The script took parameters for the

相关标签:
3条回答
  • 2020-12-28 09:29

    So let's assume your command is below

    python app.py "URL" "APIKEY" "filepath"
    

    So you will put your Dockerfile in below fashion

    FROM python:3.6
    WORKDIR /app
    COPY app.py .
    ENTRYPOINT ["python", "app.py"]
    

    Then the person running the docker container would do it like below

    docker run -v /home/tarun/project/filetoparse.yaml:/config.yaml <yourimagename> "URL" "APIKEY" /config.yaml
    

    If you want to give more flexibility you an can even use environment variables

    docker run -v /home/tarun/project/filetoparse.yaml:/config.yaml -e APIKEY="XYZ" <dockerimage> "URL" /config.yaml
    

    And then in your script you can read it using os.environ['APIKEY']

    0 讨论(0)
  • 2020-12-28 09:34

    The way you do it depends on how your using docker. If you want to run your script in an already running container, you can use exec:

    docker exec <yourContainerName> python <yourScript> <args>
    

    Alternatively, if you have a docker image where your script is the ENTRYPOINT, any arguments you pass to the docker run command will be added to the entrypoint.

    So, if your docker file looks like this:

    FROM yourbase
    ....
    ENTRYPOINT <yourScript>
    

    Then you can just run the script by running the container itself:

    docker run --rm <yourImageName> <args>
    

    Based on your comment below, it looks like you want this option. You should change your dockerfile to specify

    ENTRYPOINT ["python","./script.py"]
    

    (instead of using CMD) and then you can run via:

    docker run --rm <yourImageName>  -a API_KEY - f FILENAME -o ORG_ID
    
    0 讨论(0)
  • 2020-12-28 09:38

    Inside Dockerfile, i use the CMD command like this:

    FROM python:3
    COPY ./app /app
    WORKDIR /app
    RUN pip install --upgrade pip
    RUN pip install --no-cache-dir -r req.pip
    CMD ["python","start.py","(api-url) ","(api-key)","(file-path)"]
    

    Note Per each args/params, separate with coma

    If you are using flags, you will need to split

    CMD ["python","start.py","-u","(api-url) ","-k","(api-key)","-f","(file-path)"]
    
    0 讨论(0)
提交回复
热议问题