Skip to content Skip to sidebar Skip to footer

Need To Run Docker Run Command Inside Python Script

My Docker Command is: docker run --rm wappalyzer/cli https://wappalyzer.com When I run my python script: #!/usr/bin/python from subprocess import call import json import os import

Solution 1:

As @AndyShinn says, Python is not a shell language, but you can call to docker as if you were running a shell command:

#!/usr/bin/python
import subprocess

with open("/tmp/output.log", "a") as output:
    subprocess.call("docker run --rm wappalyzer/cli https://wappalyzer.com", shell=True, stdout=output, stderr=output)

With this approach you don't need to import docker.

Solution 2:

This isn't valid Python code. If you are just looking to run a container and passing a command as an argument, you could do something like this:

#!/usr/bin/env pythonimport sys
import docker

image = "wappalyzer/cli"

client = docker.from_env()
client.containers.run(image,  sys.argv[1], True)

But you should read up more about Python and running processes from Python if that is what you are after. Python is not a shell language and you can't just use shell commands inline.

Solution 3:

You can use a pip package named docker and use it to connect to the Docker. The difference between running a command in subProcess and this solution is the format. You can manage your images, containers, and everything a CLI is capable of.

Check it out here: https://docker-py.readthedocs.io/en/stable/

Sample:

import docker
client = docker.from_env()

client.containers.run("ubuntu", "echo hello world")

# or

client.containers.run("bfirsh/reticulate-splines", detach=True)

# you can even stream your output like this:for line in container.logs(stream=True):
   print(line.strip())

All code samples are available at the source URL I mentioned.

Solution 4:

UPDATE : 2022-03-22

We now have python-on-whales A Docker client for Python. Works on Linux, macOS, and Windows, for Python 3.7 and above.

>>>from python_on_whales import docker>>>output = docker.run("hello-world")>>>print(output)
Hello from Docker! This message shows that your installation appears to be 
working correctly.
>>>from python_on_whales import DockerClient>>>docker = DockerClient(compose_files=["./my-compose-file.yml"])>>>docker.compose.build()>>>docker.compose.up()...>>>docker.compose.down()

Post a Comment for "Need To Run Docker Run Command Inside Python Script"