I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:

a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:

(pid,status) = os.wait()
(exitstatus, signum) = decode(status) 

7 Answers

11
Mark Harrison On Best Solutions

This will do what you want:

signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
1
Derek Park On

You can unpack the status using bit-shifting and masking operators.

low = status & 0x00FF
high = (status & 0xFF00) >> 8

I'm not a Python programmer, so I hope got the syntax correct.

0
Patrick On

The folks before me've nailed it, but if you really want it on one line, you can do this:

(signum, exitstatus) = (status & 0xFF, (status >> 8) & 0xFF)

EDIT: Had it backwards.

12
Jason Pratt On

To answer your general question, you can use bit manipulation techniques:

pid, status = os.wait()
exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8

However, there are also built-in functions for interpreting exit status values:

pid, status = os.wait()
exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status )

See also:

  • os.WCOREDUMP()
  • os.WIFCONTINUED()
  • os.WIFSTOPPED()
  • os.WIFSIGNALED()
  • os.WIFEXITED()
  • os.WSTOPSIG()
2
RobM On

You can get break your int into a string of unsigned bytes with the struct module:

import struct
i = 3235830701  # 0xC0DEDBAD
s = struct.pack(">L", i)  # ">" = Big-endian, "<" = Little-endian
print s         # '\xc0\xde\xdb\xad'
print s[0]      # '\xc0'
print ord(s[0]) # 192 (which is 0xC0)

If you couple this with the array module you can do this more conveniently:

import struct
i = 3235830701  # 0xC0DEDBAD
s = struct.pack(">L", i)  # ">" = Big-endian, "<" = Little-endian

import array
a = array.array("B")  # B: Unsigned bytes
a.fromstring(s)
print a   # array('B', [192, 222, 219, 173])
2
tzot On
exitstatus, signum= divmod(status, 256)
0
Barish Ahsen On
import amp as amp
import status
signum = status &amp; 0xff
exitstatus = (status &amp; 0xff00) &gt;&gt; 8