1

我使用 os.system 运行 make 命令

os.system('make -C mydir/project all')

我想看看make是否失败。系统文档声明返回代码的格式与wait()

Wait for completion of a child process, and return 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.

所以如果make(或其他应用程序)返回-1,我必须将0xFFxx(我并不关心被调用的pid)转换为-1。右移后,我得到 0xFF,但我无法将其转换为 -1,它总是打印 255。

那么,在 python 中,如何将 255 转换为 -1,或者如何告诉解释器我的 255 实际上是一个 8 位有符号整数?

4

2 回答 2

7
if number > 127:
  number -= 256
于 2012-06-15T19:15:28.100 回答
3

尽管 Ignacio 的答案对于这种情况可能会更好,但从特殊格式的数据中解包字节的一个很好的通用工具是struct

>>> val = (255 << 8) + 13
>>> struct.unpack('bb', struct.pack('H', val))
(13, -1)
于 2012-06-15T19:15:47.453 回答