# 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().
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With