thiiiiiking
thiiiiiking

Reputation: 1233

How can I control docker using python script

Such as a python file example.py:

import os

containerId = "XXX"
command = "docker exec -ti " + containerId + "sh"
os.system(command)

when I execute this file using "python example.py", I can enter a docker container, but I want to execute some other commands inside the docker.

I tried this:

import os

containerId = "XXX"
command = "docker exec -ti " + containerId + "sh"
os.system(command)
os.system("ps")

but ps is only executed outside docker after I exit the docker container,it can not be executed inside docker.

so my question is how can I execute commands inside a docker container using the python shell.

By the way, I am using python2.7. Thanks a lot.

Upvotes: 3

Views: 1030

Answers (1)

Chris
Chris

Reputation: 3466

If the commands you would like to execute can be defined in advance easily, then you can attach them to a docker run command like this:

docker run --rm ubuntu:18.04 /bin/sh -c "ps"

Now if you already have a running container e.g.

docker run -it --rm ubuntu:18.04 /bin/bash

Then you can do the same thing with docker exec:

docker exec ${CONTAINER_ID} /bin/sh -c "ps"

Now, in python this would probably look something like this:

import os

containerId = "XXX"
in_docker_command = "ps"
command = 'docker exec ' + containerId + ' /bin/sh -c "' + in_docker_command  + '"'
os.system(command)

This solution is useful, if you do not want to install an external dependency such as docker-py as suggested by @Szczad

Upvotes: 1

Related Questions