It depends what you're trying to do but I may be doing something similar. I'm building my dockers in minikube and have a python script that I use to build those dockers.
Before I run the docker build I need to make sure the right environment variables are set, meaning I need to run
eval $(minikube -p minikube docker-env)
Which generates a bunch of statements that you're meant to run in the shell (typically with an eval)
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.49.2:2376"
export DOCKER_CERT_PATH="/home/aluchko/.minikube/certs"
export MINIKUBE_ACTIVE_DOCKERD="minikube"
# To point your shell to minikube's docker-daemon, run:
# eval $(minikube -p minikube docker-env)
To be able to trigger my builds in python I need these environment variables set when I my docker build commands.
Now there's basically two ways to do this (aside from doing the eval in a wrapper around your script). Both ways involve getting the that string with the export commands.
output = subprocess.check_output(['minikube', '-p', 'minikube', 'docker-env'])
Parse the results of the minikube (or docker-machine command) and set those variables in the shell for future subprocesses. You can be a bit sloppy with the RE since you know the output of the docker-machine command. The shell=True is just for the echo.
output = subprocess.check_output(['minikube', '-p', 'minikube', 'docker-env'])
import re
export_re = re.compile('export ([A-Z\_]+)="(.*)"\\n')
export_pairs = export_re.findall(output.decode("UTF-8"))
build_env = os.environ.copy()
for k,v in export_pairs:
build_env[k] = v
subprocess.run('echo $DOCKER_HOST', shell=True, env=build_env)
A bit sloppier, and more prone to injection attacks, just sandwich the strings together so all your commands are basically a script that starts with a bunch of exports, this isn't nearly as clean and locks you into using the shell=True subprocess functionality, but it does work.
output = subprocess.check_output(['minikube', '-p', 'minikube', 'docker-env'])
extended_output = output + b"\necho $DOCKER_HOST"
print(extended_output)
subprocess.run(extended_output, shell=True)