Chinaunix

标题: 求助:commands.getstatusoutput的错误返回值和shell中的不一样? [打印本页]

作者: xyz_hh    时间: 2012-01-29 15:31
标题: 求助:commands.getstatusoutput的错误返回值和shell中的不一样?
本帖最后由 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')
>>>

作者: thword1    时间: 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位操作就可以了。


作者: xyz_hh    时间: 2012-01-30 09:56
明白了,万分感谢!
作者: lastfile    时间: 2012-01-30 15:59
路过学习




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2