Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch a subprocess.call error with Python?

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?`
like image 888
cbll Avatar asked Dec 06 '22 13:12

cbll


1 Answers

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")
like image 125
Eric Renouf Avatar answered Dec 22 '22 09:12

Eric Renouf