2008-08-13 156 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) 
相關問題