tags:

views:

435

answers:

6

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)
+5  A: 

This will do what you want:

signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
Mark Harrison
Scott Griffiths
redundant, but I thought it was a bit more clear.
Mark Harrison
+1  A: 

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.

Derek Park
A: 

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.

Patrick
+8  A: 

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 funtions 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()
Jason Pratt
A: 

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])
RobM
+1  A: 
exitstatus, signum= divmod(status, 256)
ΤΖΩΤΖΙΟΥ