2008-08-13 159 views
10

我试图解码Python os.wait()函数的结果。这将返回,根据Python文档:如何在Python中将整数视为一个字节数组?

包含其PID和退出状态指示的元组:一个16位的数,其低字节是杀死处理的信号数量,并且其高字节为出射状态(如果信号编号为零);如果生成核心文件,则设置低字节的高位。

如何解码退出状态指示(这是一个整数)来获取高位和低位字节?具体而言,如何实现在下面的代码片段中使用的解码功能:

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

回答

11

这会做你想要什么:

signum = status & 0xff 
exitstatus = (status & 0xff00) >> 8 
+0

虽然`&0xff00`是多余的,如果`status`真的是只有16位。 – 2009-08-13 15:57:12

1

可以解压使用bit-shiftingmasking运营商的地位。

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

我不是Python程序员,所以我希望得到正确的语法。

0

乡亲面前me've钉,但如果你真的想在同一行,你可以这样做:

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

编辑:弄错了。

11

要回答你一般的问题,你可以使用bit manipulation技术:

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

然而,也有built-in functions解释退出状态值:

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

参见:

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

你可以得到你的突破诠释成的无符号字节与struct模块的字符串:

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) 

如果用array夫妇此模块可以做到这一点更方便:

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
exitstatus, signum= divmod(status, 256) 
相关问题