1

I am trying to 'port' this (working) shell command:

IMAGE_NAME="myimage" CONTAINER_NAME="myname" docker run -d --name $CONTAINER_NAME $IMAGE_NAME tail -f /dev/null 

to start a container from an image to python with:

import subprocess IMAGE_NAME="myimage" CONTAINER_NAME="myname" subprocess.check_output(['docker', 'run',"-d","--name %s" % CONTAINER_NAME,"%s" % IMAGE_NAME]) 

but if fails with:

unknown flag: --name myname See 'docker run --help'. 

Any suggestions?

2
  • Did you docker run --help? Commented Dec 19, 2017 at 23:23
  • No, my problem is my lack of understanding of how to combine command line args/options in python Commented Dec 19, 2017 at 23:27

3 Answers 3

5

Docker has its python library exposing the Docker API so you can work with containers in a programmatic way, calling methods on them, etc.

https://github.com/docker/docker-py

If you want to stick to the subprocess way, you need to put each argument to a separate element in the list you pass to check_output(). Note that arguments are separated by a whitespace, regardless of whether one argument is a value to a switch, like in --name name - those are still two arguments. Of course, if arguments are grouped in quotes, e.g. --name "a name", then the whole a name part would be a single element in the subprocess call.

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

Comments

2

Everywhere that you put a space in the arguments should be a different element in the list. It thinks that "--name myname" is a single flag. Have you tried:

subprocess.check_output(['docker', 'run', '-d', '--name', CONTAINER_NAME, IMAGE_NAME]) 

Comments

1

Piece of code bellow based on https://github.com/docker/docker-py library

import docker client = docker.DockerClient(base_url='unix://var/run/docker.sock') container = client.containers.run('28_googleplay_root_x86_64:latest', name='your_name', detach=True, ports={'5556/tcp': 5556, '5555/tcp': 5555}, devices=['/dev/kvm']) 

Container will be created and detached. Library documentation can be find here https://docker-py.readthedocs.io/en/stable/index.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.