Python检查shell命令的退出状态

2024-04-27 17:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

运行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

#闪存raid固件

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

#固件闪存的返回状态

?

建议使用“subprocess.check_output()”的一个资源,但是,我不确定如何将其合并到函数OSinfo()中。


Tags: the函数命令truereturnstdoutresultshell
2条回答

如果您只想return 1如果存在非零退出状态,请使用check_call,任何非零退出状态都将引发我们捕获的错误,否则return 1将是osstdout

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

如果传递参数列表,则也不需要shell=True。

与其使用osstdout.stdout.read()来获取子进程的stdout,不如使用^{}来获取子进程的stdout,这将阻塞直到子进程终止。完成后,属性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)

相关问题 更多 >