如何解释Python命令中的状态代码.getstatusoutput()

时间:2009-10-08 04:43:50

标签: python command subprocess exit-code

related question中,我询问在哪里可以找到C函数的文档“wait”。这是尝试找出commands.getstatusoutput()模块的返回码。 Stackoverflow通过,但文档没有帮助。这就是困扰我的:

#!/usr/bin/python
import commands
goodcommand = 'ls /'
badcommand = 'ls /fail'
status, output = commands.getstatusoutput(goodcommand)
print('Good command reported status of %s' % status)
status, output = commands.getstatusoutput(badcommand)
print('Bad command reported status of %s' % status)

在OS X(Leopard)上运行时,我得到以下输出:(符合文档。)

$ python waitest.py 
Good command reported status of 0
Bad command reported status of 256

在OS X上,执行“ls / fail; echo $?”得到以下输出:

$ ls /fail ; echo $?
ls: /fail: No such file or directory
1

在Linux(Ubuntu Hardy)上运行时,我得到以下输出:

$ python waitest.py 
Good command reported status of 0
Bad command reported status of 512

在Ubuntu上,执行“ls / fail”会得到2:

$ ls /fail ; echo $?
ls: cannot access /fail: No such file or directory
2

所以Python似乎将状态代码乘以256.嗯?这是在某处记录的吗?

4 个答案:

答案 0 :(得分:11)

os模块中有一组函数(os.WIFCONTINUEDos.WIFSTOPPEDos.WTERMSIGos.WCOREDUMPos.WIFEXITED,{{1 }},os.WEXITSTATUSos.WIFSIGNALED),对应于wait(2)手册中的宏。您应该使用它们来解释状态代码。

例如,要获取退出代码,您应该使用os.WSTOPSIG

更好的想法是切换到os.WEXITSTATUS(status)模块。

答案 1 :(得分:4)

哇。它乘以256的洞察力让我在那里。搜索“python命令+256”让我看到一篇Python Module Of The Week文章,解释了发生了什么。

以下是该页面的摘录:

  

函数getstatusoutput()运行一个   通过shell命令并返回   退出代码和文本输出(stdout   和stderr相结合)。退出代码   与C函数相同   wait()或os.wait()。代码是一个   16位数。低字节包含   杀死的信号   处理。当信号为零时,   高字节是的退出状态   程序。如果生成了核心文件,   设置低字节的高位。

道格的一些代码:

from commands import *

def run_command(cmd):
    print 'Running: "%s"' % cmd
    status, text = getstatusoutput(cmd)
    exit_code = status >> 8
    signal_num = status % 256
    print 'Signal: %d' % signal_num
    print 'Exit  : %d' % exit_code
    print 'Core? : %s' % bool(exit_code / 256)
    print 'Output:'
    print text
    print

run_command('ls -l *.py')
run_command('ls -l *.notthere')
run_command('echo "WAITING TO BE KILLED"; read input')

答案 2 :(得分:3)

查看commands.py

def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    import os
    pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == '\n': text = text[:-1]
    return sts, text

我们看到sts包含os.popen(...).close()的值。查看that documentationos.popen(...).close()会返回os.wait的值:

  

os.wait()

     

等待子进程完成,并返回一个包含其pid和退出状态指示的元组:一个16位数字,其低字节是杀死进程的信号编号,其高字节是退出状态(如果信号编号为零);如果生成核心文件,则设置低字节的高位。可用性:Unix。

重点是我的。我同意这种“编码”并不是非常直观,但至少它一目了然地表明它正在被乘法/位移。

答案 3 :(得分:0)

我认为代码检测不正确。

“如果生成了核心文件,则设置低字节的高位。”意思是128。

所以我认为核心线应该是

print 'Core? : %s' % bool(status & 128)