How to interpret status code in Python commands.getstatusoutput ()

In a related question , I asked where to find the documentation for the wait function. It was an attempt to find out return codes for the commands.getstatusoutput () module. Stackoverflow passed, but the documentation did not help. Here's what puzzles me:

#!/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)

When running on OS X (Leopard), I get the following output: (which matches the documentation.)

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

On OS X running "ls / fail; echo $?" gets the following result:

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

When running on Linux (Ubuntu Hardy), I get the following output:

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

On Ubuntu, running "ls / fail" gets 2:

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

So, Python seems to be multiplying state codes by 256. Huh? Is it documented anywhere?

+5
4

os (os.WIFCONTINUED, os.WIFSTOPPED, os.WTERMSIG, os.WCOREDUMP, os.WIFEXITED, os.WEXITSTATUS, os.WIFSIGNALED, os.WSTOPSIG), wait (2). .

, , os.WEXITSTATUS(status)

subprocess.

+10

. , 256, . " python +256" Python Module of the Week, , .

:

getstatusoutput() (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')
+4

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(). , os.popen(...).close() os.wait:

os.wait()

, pid : 16- , , , , ( ); , . : Unix.

The emphasis was mine. I agree that this “encoding” is not terribly intuitive, but at least at first glance it was obvious that it was multiplied / bit-shifted.

+3
source

I think the code detection is wrong.

"If the main file was created, the most significant bit of the low byte is set." means 128.

so I think the main line should be

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

All Articles