Reputation: 59202
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)
Upvotes: 15
Views: 5218
Reputation: 46846
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.
Upvotes: 1
Reputation: 13264
To answer your general question, you can use bit manipulation
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:
Upvotes: 13
Reputation: 100
import amp as amp
import status
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
Upvotes: 0
Reputation: 8945
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])
Upvotes: 2
Reputation: 92520
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.
Upvotes: 0
Reputation: 304474
This will do what you want:
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
Upvotes: 14