MIDE11
MIDE11

Reputation: 3530

Call in python return code status only

I have the following code in python:

i = call(["salt-cloud", "-m", fileName, "--assume-yes"])
print (i)

i is always 0, because the operation is finished.

The problem is that I want to get the output of this operation. In our case:

window:
    ----------
    Error:
        ----------
        Not Deployed:
            Failed to start Salt on host window

is the output of running salt-cloud -m fileName --assume-yes, and it is an indication that error raised in this process, and I want to know it.

How can I achieve it in Python?

Upvotes: 1

Views: 106

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

Use check_output and catch a CalledProcessError which will be raised for any non-zero exit status:

from subprocess import check_output, CalledProcessError    

try:
    out = check_call(["salt-cloud", "-m", fileName, "--assume-yes"]) 
    print(out)   
except CalledProcessError as e:
    print(e.message)

If you are using python < 2.7 you will need Popen, check_call and check_output were added in python 2.7:

from subprocess import Popen, PIPE

p = Popen(["salt-cloud", "-m", filename, "--assume-yes"],stderr=PIPE,stdout=PIPE)

out, err = p.communicate()

print( err if err else out)

Upvotes: 3

maahl
maahl

Reputation: 547

Assuming you're using subprocess.call, you might want to take a look at subprocess.check_output(), which returns the output of the subprocess as a byte string.

Upvotes: 2

Related Questions