I'm trying to download a specific Docker image, where the user will input a version. However, if the version doesn't exist, Docker will throw an error.
I'm using subprocess.call
to pipe to the Terminal from Python 3.
Sample code:
from subprocess import call
containerName = input("Enter Docker container name: ")
swVersion = input("Enter software version: ")
call(["docker", "run", "--name", "{}".format(containerName),
"--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)])
If the version isn't found, docker will output in the Terminal:
docker: Error response from daemon: manifest for user/software:8712378 not found.
How do I catch this error within the Python script?
Something along the lines of:
try:
call(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)])
except:
# How do I catch the piped response code here?`
If you are fine with the program writing its output to stderr
and you not directly interacting with it, the easiest way to do what you are asking is to use check_call
instead of call
. check_call
will raise an exception if the command it's running exits with anything other than 0
as its status.
try:
check_call(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)])
except CalledProcessError:
print("That command didn't work, try again")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With