exc*_*ror 5 python subprocess exit-code
#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
Run Code Online (Sandbox Code Playgroud)
#flash raid固件
OSinfo('MegaCli -adpfwflash -f ' + imagefile + ' -noverchk -a0')
Run Code Online (Sandbox Code Playgroud)
#返回固件闪存状态
?
Run Code Online (Sandbox Code Playgroud)
一个资源建议使用'subprocess.check_output()',但是,我不知道如何将其合并到函数OSinfo()中.
如果您只是想要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
Run Code Online (Sandbox Code Playgroud)
如果传递args列表,也不需要shell = True.
而不是使用osstdout.stdout.read(),以获得stdout您可以改用子进程osstout.communicate()这将阻止,直到子进程终止.完成此操作后,osstout.returncode将设置包含子进程返回码的属性.
然后你的函数可以写成
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)
Run Code Online (Sandbox Code Playgroud)