Search code examples
pythoncommandsubprocessexit-code

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


In a related question, I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't 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 run 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, doing an "ls /fail ; echo $?" gets the following output:

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

When run 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, doing "ls /fail" gets a 2:

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

So Python appears to be multiplying status codes by 256. Huh? Is this documented somewhere?


Solution

  • There is a set of functions in os module (os.WIFCONTINUED, os.WIFSTOPPED, os.WTERMSIG, os.WCOREDUMP, os.WIFEXITED, os.WEXITSTATUS, os.WIFSIGNALED, os.WSTOPSIG), which correspond to macros from wait(2) manual. You should use them to interpret the status code.

    For example, to get the exit code you should use os.WEXITSTATUS(status)

    A better idea would be to switch to subprocess module.