7

# function to run shell commands

def OSinfo(runthis):
        #Run the command in the OS
        osstdout = subprocess.Popen(runthis, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
        #Grab the stdout
        theInfo = osstdout.stdout.read() #readline()
        #Remove the carriage return at the end of a 1 line result
        theInfo = str(theInfo).strip()
        #Return the result
        return theInfo

# flash raid firmware

OSinfo('MegaCli -adpfwflash -f ' + imagefile + ' -noverchk -a0')

# return status of the firmware flash

?

One resource recommended using 'subprocess.check_output()', however, I'm not sure how to incorporate this into function OSinfo().

3
  • do you just want to check that the return code is 0? Commented Jan 19, 2015 at 18:24
  • Yes. Check if it's zero, if not then exit 1. Commented Jan 19, 2015 at 18:43
  • so you don't care about any output, just a non 0 exit status? Commented Jan 19, 2015 at 18:44

2 Answers 2

9

If you just want to return 1 if there is a non-zero exit status use check_call, any non zero exit status will raise an error which we catch and return 1 else osstdout will be 0:

import subprocess
def OSinfo(runthis):
        try:
            osstdout = subprocess.check_call(runthis.split())
        except subprocess.CalledProcessError:
            return 1
        return osstdout

You also don't need shell=True if you pass a list of args.

Sign up to request clarification or add additional context in comments.

Comments

7

Instead of using osstdout.stdout.read() to get the stdout of the subprocess you can instead use osstout.communicate() This will block until the subprocess terminates. Once this is done the attribute osstout.returncode will be set containing the return code of the subprocess.

Your function could then be written as

def OSinfo(runthis):
    osstdout = subprocess.Popen(runthis, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)

    theInfo = osstdout.communicate()[0].strip()

    return (theInfo, osstout.returncode)

1 Comment

For Python 2.7 on Windows, it throws an exception: ValueError: close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr :-(

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.