3

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.