如何在Python中将整数视为字节数组?

Lor*_*ein 10 python

我正在尝试解码Python os.wait()函数的结果.根据Python文档,这将返回:

包含其pid和退出状态指示的元组:一个16位数字,其低字节是杀死进程的信号编号,其高字节是退出状态(如果信号编号为零); 如果生成核心文件,则设置低字节的高位.

如何解码退出状态指示(这是一个整数)以获得高字节和低字节?具体来说,我如何实现以下代码片段中使用的解码函数:

(pid,status) = os.wait()
(exitstatus, signum) = decode(status) 
Run Code Online (Sandbox Code Playgroud)

Jas*_*att 12

要回答您的一般问题,您可以使用位操作技术:

pid, status = os.wait()
exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8
Run Code Online (Sandbox Code Playgroud)

但是,还有用于解释退出状态值的内置函数:

pid, status = os.wait()
exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status )
Run Code Online (Sandbox Code Playgroud)

也可以看看:

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


Mar*_*son 11

这将做你想要的:

signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
Run Code Online (Sandbox Code Playgroud)

  • 多余,但我认为这更清楚了。 (2认同)