Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check exit status of a shell command

# 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().

like image 230
except UserError Avatar asked Jan 19 '15 17:01

except UserError


2 Answers

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.

like image 137
Padraic Cunningham Avatar answered Sep 18 '22 22:09

Padraic Cunningham


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)
like image 38
Simon Gibbons Avatar answered Sep 21 '22 22:09

Simon Gibbons