免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 13336 | 回复: 3
打印 上一主题 下一主题

求助:commands.getstatusoutput的错误返回值和shell中的不一样? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-01-29 15:31 |只看该作者 |倒序浏览
本帖最后由 xyz_hh 于 2012-01-29 15:31 编辑

看下面例子,执行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')
>>>

论坛徽章:
0
2 [报告]
发表于 2012-01-29 19:14 |只看该作者
本帖最后由 thword1 于 2012-01-29 22:47 编辑

其实这个返回值256就是十六进制的0x100,其高位就是1。

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

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

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

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

至于为什么会这样,
  1. os.wait()

  2.     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位操作就可以了。

论坛徽章:
0
3 [报告]
发表于 2012-01-30 09:56 |只看该作者
明白了,万分感谢!

论坛徽章:
0
4 [报告]
发表于 2012-01-30 15:59 |只看该作者
路过学习
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP