commands.getstatusoutput的错误返回值和shell中的不一样?

该问题是一个博主的问答,在此记录一下,原文地址:http://bbs.chinaunix.net/thread-3666310-1-1.html

博主问题:
看下面例子,执行cat file命令(file文件不存在),shell中的返回值是1,而python的commands.getstatusoutput返回值是256,如何才能获得和shell中一致的返回值?

[root@myssl ~]# cat file
cat: file: 没有那个文件或目录
[root@myssl ~]# echo $?
1
[root@myssl ~]#
[root@myssl ~]# python
Python 2.4.3 (#1, Jun 11 2009, 14:09:37) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import commands
>>> commands.getstatusoutput('cat file')
(256, 'cat: file: \xc3\xbb\xd3\xd0\xc4\xc7\xb8\xf6\xce\xc4\xbc\xfe\xbb\xf2\xc4\xbf\xc2\xbc')
>>> 
回答:
其实这个返回值256就是十六进制的0x100,其高位就是1。

这是调用了os.wait()的缘故(*nix下)。

类似的,如果你输入一个不存在的程序,比如xxx。

shell中的$?返回为127,在这里会显示32512,正是十六进制的0x7f00,其高位0x7f就是十进制的127。

另外,使用os.system('command')也有同样的效果。

至于为什么会这样,
os.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.
复制代码
这是系统函数wait()这么实现的缘故,从某种角度来说,你也可以认为这是python的一个小bug,没有把这个返回值做进一步处理。当然,最初没有做进一步处理,也可能有另外的考量。

--------------------------

要取出这个返回值,对该值进行右移8位操作就可以了。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值