How to execute a local python script into a docker from another python script?
Asked Answered
B

3

8

Let me clarify what I want to do.

I have a python script in my local machine that performs a lot of stuff and in certain point it have to call another python script that must be executed into a docker container. Such script have some input arguments and it returns some results.

So i want to figure out how to do that.

Example:

def function()
    do stuff
         .
         .
         .
    do more stuff

    ''' call another local script that must be executed into a docker'''

    result = execute_python_script_into_a_docker(python script arguments)

The docker has been launched in a terminal as:

docker run -it -p 8888:8888 my_docker
Boito answered 26/7, 2017 at 10:23 Comment(0)
A
21

You can add your file inside docker container thanks to -v option.

docker run -it -v myFile.py:/myFile.py -p 8888:8888 my_docker

And execute your python inside your docker with : py /myFile.py

or with the host:

docker run -it -v myFile.py:/myFile.py -p 8888:8888 my_docker py /myFile.py

And even if your docker is already running

docker exec -ti docker_name py /myFile.py

docker_name is available after a docker ps command.

Or you can specify name in the run command like:

docker run -it --name docker_name -v myFile.py:/myFile.py -p 8888:8888 my_docker

It's like:

-v absoluteHostPath:absoluteRemotePath

You can specify folder too in the same way:

-v myFolder:/customPath/myFolder

More details at docker documentation.

Adrianaadriane answered 26/7, 2017 at 10:52 Comment(2)
Yes i'm aware that i can do that, but the question here is how can i do it from another local python script, i'm not able to figure out how do that, I mean the script_1 must run in local machine, and then in certain point of the rutine it must call the other script (script_2) in the docker...Boito
You have to execute from shell. Try to launch your command in shell with python : #89728Adrianaadriane
A
3

You can use docker's python SDK library. First you need to move your script there, I recommend you do it when you create the container or when you start it as Callmemath mentioned:

docker run -it -v myFile.py:/myFile.py -p 8888:8888 my_docker

Then to run the script using the library:

...
client = docker.client.from_env()
container = client.containers.get(CONTAINER_ID)
exit_code, output = container.exec_run("python your_script.py script_args")
... 
Arras answered 17/7, 2019 at 8:17 Comment(0)
B
1

you have to use docker exec -it image_name python /filename

Note: To use 'docker exec' you must run the container using docker run

Bary answered 26/7, 2017 at 10:57 Comment(2)
how do we keep it running?Brebner
@NikhilVJ When running docker from terminal you can add the flag -d to detach the execution of docker from terminal, then you can use the same terminal to execute the command docker exec... or use another terminalBoito

© 2022 - 2024 — McMap. All rights reserved.