[英]Python check exit status of a shell command
# function to run shell commands #function运行shell命令
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 #flash raid固件
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(). 一个资源建议使用'subprocess.check_output()',但是,我不知道如何将其合并到函数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
: 如果你只想要
return 1
如果有一个非零退出状态使用check_call
,任何非零退出状态将引发一个错误,我们捕获并return 1
否则osstdout
将为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. 如果传递args列表,也不需要shell = True。
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. 您可以使用
osstout.communicate()
而不是使用osstdout.stdout.read()
来获取子osstdout.stdout.read()
的stdout
,这将阻塞,直到子osstout.communicate()
终止。 Once this is done the attribute osstout.returncode
will be set containing the return code of the subprocess. 完成此操作后,将设置属性
osstout.returncode
其中包含子osstout.returncode
的返回码。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.