Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to run docker run command inside python script

Tags:

python

docker

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 docker

docker run --rm wappalyzer/cli "MYURL"

it says

File "t.py", line 7
    docker run --rm wappalyzer/cli "MYURL"
             ^
SyntaxError: invalid syntax

My os is ubuntu 14.04 and I am using ubuntu terminal.

like image 574
Prageeth Avatar asked Jul 01 '17 14:07

Prageeth


2 Answers

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 python
import 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.

like image 27
Andy Shinn Avatar answered Sep 28 '22 13:09

Andy Shinn


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.

like image 88
Robert Avatar answered Sep 28 '22 12:09

Robert