1

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?

1
  • you can use subprocess.Popen Commented Mar 30, 2015 at 13:24

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

5 Comments

But it returns 0, even if the process is failed (like in my example - window was not deployed, but code 0 was returned)
Then it is a normal exit status. try check_output. Does it ever raise a non-zero exit status?
I try the following: ` try: from subprocess import check_output except Exception as e: print e` and it gives me the following error:cannot import name check_output
are you using python2.6?
then use the second part of the answer
2

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.

3 Comments

Should I use it this way: import subprocess subprocess.check_output(["salt-cloud", "-m", fileName, "--assume-yes"])
You'll have to get the output in a variable if you want to use it. output = subprocess.check_output(...)
I try the following: ` try: from subprocess import check_output except Exception as e: print e` and it gives me the following error:cannot import name check_output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.